簡體   English   中英

在javascript中如何在另一個原型方法中調用一個原型方法?

[英]In javascript how can I call one prototype method in another prototype method?

假設我有一個功能:

function test(){}

test.prototype.method01=function(){
    //do something
}

test.prototype.method02=function(){
    //how can I call the method01?
    //this.method01()...?
    //but the chrome through an error:
    //Uncaught TypeError: Object #<HTMLImageElement> has no method 'method01'
}

編輯:實際上方法01是這樣的:

test.prototype.method02=function(){
    $('.cpy').resizable({

    }).draggable({
        start:function(e,ui){
            this.method01();
        }
    });
}
test.prototype.method02=function(){
    var testThing = this;
    $('.cpy').resizable({

    }).draggable({
        start:function(e,ui){
            testThing.method01();
        }
    });
}

您必須在另一個局部變量中保留this引用,以便回調函數在調用另一個方法時可以使用它。 this引用綁定在每個函數調用上,包括調用回調函數,例如您在“.draggable()”設置中使用的函數。 當被調用時, this將在“method02”函數中設置為與this不同的內容。

是的,你可以像在這個問題的其他答案中那樣在詞法范圍內手動緩存this 但是,我建議的替代方法是使用$.proxyfunction.bind作為$.proxy創建綁定方法。

綁定方法往往被稱之為具有穩定this 我發現它們更具可讀性,而不是在更高范圍內this進行奇怪的命名

怎么樣?

test.prototype.method02=function(){
     this.method01.apply(this);
     // do some other stuff
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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