当从另一个上下文中调用方法时,' this '未定义

`this` is undefined when calling method from another context

本文关键字:未定义 this 方法 另一个 上下文 调用      更新时间:2023-09-26

这是我第一次为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 -关键字变得非常复杂,这让我觉得我的设计可能有缺陷。

这个问题有解决方案吗,或者我应该重构它吗?

肯定会变得复杂,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();

部分语法错误&风格问题——这是一个简短的更正

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);
}

我已经将这两个函数移到了构造函数之外,这样它们就不会在每次调用构造函数时都被重新创建。

与_.bind(this)"this"引用被传递到你的函数的范围(我认为这比创建另一个var更漂亮)。

var reff = new NewApp('namename');

你现在可以开始调用你的函数了:

ref.logic(); 

也许这个方法对你有用?