JS将函数变成对象而不使用“;返回“;在函数表达式中
JS turning a function into an object without using "return" in the function expression
我在一个框架中看到过(遇到过一次,再也没有遇到过),开发人员定义了这样的模块:
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();
相关文章:
- ES6构造函数返回基类的实例
- 从函数返回角度承诺
- 如何从jquery函数返回变量
- 根据是否解析了 Promise 从函数返回值
- Javascript函数返回未定义
- 如果函数返回True,则显示Javascript按钮
- Google Sheet自定义函数返回0
- 从Ajax函数返回值
- 使用for循环从Javascript中的函数返回多个值
- 谷歌地图:函数返回未定义的值在console.log中运行良好
- 从函数中的函数返回数组时出错
- 如何从嵌套的API函数返回值
- 从Mongoose结果匿名函数返回父函数
- 函数返回错误'令牌{'
- Jquery函数返回订单问题
- Mocha/Chai测试链接到函数返回断言错误
- 从异步函数返回值
- 函数返回后更新变量
- 我如何才能继续'如果'语句来比较作为参数的多个函数返回值
- 将外部函数返回的id传递给内部函数