[英]`this` is undefined when calling method from another context
这是我第一次为JS创建OOP。 我遵循了一些教程,但是无法解决这个问题。 我知道问题所在,但我不知道解决方案
function NewApp(name){
this.name = name;
this.currentPage = 1;
this.customObjectWithMethods = //init with options and so on
}
NewApp.prototype.logic = function(){
// Note 1.
var app = this
//Note 3.
this.customObjectWithMethods.method{
if(app.currentpage < 3)
// Note 2.
app.navigate(app.logic)
}
}
NewApp.prototype.navigate = function(sender){
var app = this;
this.customObjectWithMethods.method{
app.currentpage++;
this.method(function() {
return app.currentPage === 2;
}, sender(), this.terminate);
}
}
this
引用不再适用于引用当前对象。 this.customObjectWithMethods
并重复当前函数,但是当函数再次运行时,它在方法( this.customObjectWithMethods
)上中断,因为this
方法不存在。 this
-keyword会使事情变得非常复杂,这让我觉得我的设计可能有缺陷。
有没有解决这个问题的方法,还是我应该重构它?
一些语法错误和样式问题-这是一个简短的更正
var myFunction = function(){
//code here
};
var mySecondFunction = function(){
//code here
};
function NewApp(name){
this.name = name;
this.currentPage = 1;
this.customObjectWithMethods = function(){}; //empty function so calling doesnt resolve in error
}
NewApp.prototype.logic = function(){
this.customObjectWithMethods.method = mySecondFunction.bind(this);
}
NewApp.prototype.navigate = function(sender){
this.customObjectWithMethods.method = myFunction.bind(this);
}
我已经将2个函数移到了构造函数的外面,所以每次调用构造函数时都不会重新创建它们。
使用_.bind(this),“ this”引用被传递到您的函数范围内(我认为这比创建另一个var更漂亮)。
同
var reff = new NewApp('namename');
您可以立即开始调用函数:
ref.logic();
也许这种方法对您有用?
当然它将变得复杂, this
关键字并不总是指向主要对象,而是指向其使用范围,请查看Scope以及JavaScript中的更多信息。
这是您要采取的方法,创建一个包含构造函数的变量,然后将这两个方法添加到此变量中,之后您可以调用函数:
var newApp = function newApp(name){
this.name = name;
this.currentPage = 1;
//Make a reference to your object here
var THIS = this;
this.logic = function(){
var sender = this;
THIS.customObjectWithMethods.method = function(){
if(THIS.currentpage < 3)
THIS.navigate(sender);
}
}
this.navigate = function(sender){
this.customObjectWithMethods.method = function(){
THIS.currentpage++;
this.method(function() {
return THIS.currentPage === 2;
}, sender(), this.terminate);
}
}
}
这就是如何使用构造函数及其方法:
var app = newApp("Test");
//Call the first method
app.customObjectWithMethods();
//Thenn call the second one
app.logic();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.