Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS turning a function into an object without using "return" in the function expression

i have seen in a framework (came across it once, and never again) where the developer defines a module like this:

core.module.define('module_name',function(){
    //module tasks up here
    this.init = function(){
        //stuff done when module is initialized
    }
});

since i never saw the framework again, i tried to build my own version of it and copying most of it's aspects - especially how the code looked like. i tried to do it, but i can't seem to call the module's init() because the callback is still a function and not an object. that's why i added return this

//my version
mycore.module.define('module_name',function(){
    //module tasks up here
    this.init = function(){
        //stuff done when module is initialized
    }

    //i don't remember seeing this:
    return this;
});

in mycore, i call the module this way (with the return this in the module definition):

var moduleDefinition = modules[moduleName].definition; //the callback
var module = moduleDefinition();
module.init();

how do i turn the callback function into an object but preserve the way it is defined (without the return this in the definition of the callback)?

like image 862
Joseph Avatar asked Nov 26 '25 10:11

Joseph


1 Answers

you have to use:

var module = new moduleDefinition();

and then you're going to get an object.

Oh, and maybe you want to declare init as this:

this.init = function() {

Cheers.

like image 135
Gonzalo Larralde Avatar answered Nov 29 '25 00:11

Gonzalo Larralde