Consider the following code:
function test() {
this.foo = function() {
console.log('foo');
return;
}
this.bar = function() {
console.log('bar');
return;
}
}
var action = new test();
action.foo(); //prints 'foo'
Code above works fine in case I need to call an action foo
or bar
inside action test
. However action test
itself supposed to be a callable function. I thought it would be cool if JavaScript would let me create something like this (see below) but, as expected, says:
TypeError: action is not a function
function test() {
this.foo = function() {
console.log('foo');
return;
}
this.bar = function() {
console.log('bar');
return;
}
return function() {
console.log('default');
return;
}();
}
var action= new test();
action(); //prints 'default'
action.bar(); //printf 'bar'
Is it possible to achieve something similar?
It is possible. Just create a function inside and add other properties directly to the function object:
function test() {
var result = function () {
console.log('default');
};
result.foo = function() {
console.log('foo');
return;
}
result.bar = function() {
console.log('bar');
return;
}
return result;
}
var test = new test();
test(); //prints 'default'
test.bar(); //printf 'bar'
In javascript it is possible to add properties also to functions. So that you can do something like this:
function test() {
function defaultFn() {
console.log('default');
}
defaultFn.foo = function() {
console.log('foo');
return;
}
defaultFn.bar = function() {
console.log('bar');
return;
}
return defaultFn;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With