簡體   English   中英

從另一個上下文中調用方法時,“ this”是未定義的

[英]`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);
    } 
}
  • 注意1:我需要創建一個引用,因為在那之后, this引用不再適用於引用當前對象。
  • 注意2:檢查后,我想在其他方法中做一些邏輯this.customObjectWithMethods並重復當前函數,但是當函數再次運行時,它在方法( this.customObjectWithMethods )上中斷,因為this方法不存在。
  • 注意3:這是中斷的地方,因為“ 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM