Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a function with nested functions and default function

Tags:

javascript

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?

like image 723
lolbas Avatar asked May 19 '16 17:05

lolbas


2 Answers

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'
like image 67
basilikum Avatar answered Oct 26 '22 23:10

basilikum


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;
}
like image 29
madox2 Avatar answered Oct 26 '22 23:10

madox2