我在学习模块模式时遇到困难,
能够从安装程序中运行我的函数 getData 的正确方法是什么,目前它尚未定义。
https://jsbin.com/movaleyedo/edit?html,js,console,output
var module = (function(){
var Setup = function(){
this.getData = function(){
return "data";
};
this.init = function(){
this.getData(function(err,data){
alert(data);
});
};
};
return {
init: new Setup().init
};
})();
module.init();
"TypeError: this.getData is not a function
at Object.init (movaleyedo.js:8:12)
at movaleyedo.js:17:8
at https://static.jsbin.com/js/prod/runner-3.35.9.min.js:1:13891
at https://static.jsbin.com/js/prod/runner-3.35.9.min.js:1:10820"
我创建了第二个示例,说明为什么我不明白发生了什么。
var Module = (function(){
var app = this;
var One = function(){
this.one = function(){
return 1;
}
this.getNumbers = function(){
return this.one();
}
};
var Two = function(){
this.getNumbers = function(){
return 2;
}
this.two = function(){
app.one = new One;
console.log(app.one.getNumbers()); //doesnt break
console.log(this.getNumbers());//breaks
}
};
return {
init: new Two().two
};
})();
Module.two();
基本上在 One() 内部,我可以调用 return this.one()。
但在 Two() 内我无法调用 this.getNumbers()
最佳答案
实现是同步的,调用是异步的
this.getData = function(){
return "data";
};
this.getData(function(err,data){
alert(data);
});
//should be used either
var data = this.getData();
alert(data);
//or defined as
this.getData = function(callback){
callback(null, "data");
};
另外,其他用户是对的,您只传递了该函数。在该函数中使用“this”关键字将引用其他内容。为什么不传递实例本身或创建实例?
类似这样的事情
return new Setup();
module.init();
或
return Setup;
var instance = new module();
instance.init();
关于javascript 模块模式上下文问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35369763/