![](/img/trans.png)
[英]Javascript prototype: how do I call a method within another method?
[英]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
。 但是,我建議的替代方法是使用$.proxy
或function.bind
作為$.proxy
創建綁定方法。
綁定方法往往被稱之為具有穩定this
。 我發現它們更具可讀性,而不是在更高范圍內this
進行奇怪的命名
怎么樣?
test.prototype.method02=function(){
this.method01.apply(this);
// do some other stuff
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.