当从另一个上下文中调用方法时,“ this”是未定义的

迈克尔·安杰洛

这是我第一次为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);
    } 
}
  • 注意1:我需要创建一个引用,因为在那之后,this它不再起作用以引用当前对象。
  • 注意2:检查后,我想用另一种方法做一些逻辑运算并重复当前函数,但是当该函数再次运行时,它在方法(this.customObjectWithMethods上中断,因为this不存在。
  • 注意3:这是中断的地方,因为“ this”是第一次而不是第二次起作用。

这样的this-keyword变得非常复杂,这让我认为我的设计可能有缺陷。

有没有解决这个问题的方法,还是我应该重构它?

cнŝdk

当然,它会变得很复杂,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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章