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

I've seen in a wireframe (came across it once and never again) where a developer defines a module like this:

    //module tasks up here
    this.init = function(){
        //stuff done when module is initialized


since I never saw the framework again, I tried to create my own version and copy most aspects of it - especially what the code looked like. I tried this, but I cannot name the module init()

because the callback is still a function, not an object. why i addedreturn this

//my version
    //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 return this

in the module definition):

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


How do I include a callback function in an object, but keep the definition way (without return this

in the callback definition)?


source to share

4 answers

you should use:

var module = new moduleDefinition();


and then you get the object.

Oh, and maybe you want to declare init

like this:

this.init = function() {





How about something like this (I can only guess what it looks like mycore


mycore = {
  module: {
    definitions: {},
    define: function(name, Module) {
      this.definitions[name] = new Module();

mycore.module.define('module_name', function () {
  // module tasks up here
  this.init = function () {
    // init tasks here
    console.log('init has been called');




I don't know what framework you are using or what requirements it imposes on you, but Javascript itself does not require a function to return anything, not even a function that defines an object. For example:

function car(color) {
  this.myColor = color;
  this.getColor = function() {
    return this.myColor;
  //note: no return from this function

var redCar = new car('red');
var blueCar = new car('blue');
alert(redCar.getColor());  //alerts "red"
alert(blueCar.getColor()); //alerts "blue"




Yet another alternative http://jsfiddle.net/pWryb/

function module(core){this.core = core;}
function Core(){
    this.module = new module(this);
Core.prototype.modules = {};

module.prototype.define = function(name, func){
  this.core.modules[name] = new func();
  this.core.modules[name].name = name;
  // or
  return this.core.modules[name];

var myCore = new Core();
var myModule = myCore.module.define('messageMaker', function(){
    this.init = function(){
        console.log("initializing " + this.name);





All Articles