JS将函数变成对象而不使用“;返回“;在函数表达式中

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

本文关键字:函数 返回 表达式 对象 JS      更新时间:2023-09-26

我在一个框架中看到过(遇到过一次,再也没有遇到过),开发人员定义了这样的模块:

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

由于我再也没有见过这个框架,我尝试构建自己的版本,并复制它的大部分方面,尤其是代码的外观。我试过这样做,但似乎无法调用模块的init(),因为回调仍然是一个函数,而不是一个对象。这就是我添加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;
});

mycore中,我这样调用模块(在模块定义中使用return this):

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

如何将回调函数转换为对象,但保留其定义方式(在回调的定义中没有return this)?

您必须使用:

var module = new moduleDefinition();

然后你会得到一个物体。

哦,也许你想把init声明为:

this.init = function() {

干杯。

这样的东西怎么样(我只能假设mycore是什么样子):

mycore = {
  module: {
    definitions: {},
    define: function(name, Module) {
      this.definitions[name] = new Module();
      this.definitions[name].init();
    }
  }
};
mycore.module.define('module_name', function () {
  // module tasks up here
  this.init = function () {
    // init tasks here
    console.log('init has been called');
  };
});

我不知道您使用的是什么框架,也不知道它对您提出了什么要求,但Javascript本身不需要函数返回任何内容,甚至不需要定义对象的函数。例如:

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"

另一种选择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;
  this.core.modules[name].init();
  // 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);
    }
})
myModule.init();