[英]Can not call a method from inside another method in Javascript
檢查下面的代碼,我只是在這里迷路,為什么會收到此錯誤。 請提出任何建議。 在這里,我進行了一個類測試,並添加了兩個方法check和nextfn。 我正在打電話給nextfn。
var test=function(){}
test.prototype.check=function()
{
console.log("hello from checking");
}
test.prototype.nextFn=function(){
check();
console.log("Hello from nextfn");
}
下一個
var t=new test();
t.nextfn();
錯誤是
Uncaught ReferenceError: check is not defined(…)
現在考慮另一種情況;
test.prototype.anotherFn=function()
{
var p=new Promise(function(){
this.check();
})
}
現在也出現同樣的錯誤;
Uncaught ReferenceError: check is not defined(…)
打電話時
var t=new test();
t.anotherFn();
check
功能位於test
對象的原型上。
當您像這樣調用nextFn
:
t.nextfn();
隨后的范圍將綁定到“類型” test
的t
實例。 在nextfn
中可以通過this
訪問test
的原型。
因此,使用this
訪問check
:
this.check();
這些東西令人驚訝地令人困惑。 這本書是一個很好的參考。
====
關於你的第二之情況,問題是,你試圖調用this
從具有它自己的范圍內的功能。
JavaScript中的范圍通常不是塊范圍的,而是函數范圍的 。 還有更多功能,我建議閱讀有關閉包的教程以獲得更全面的描述,但是現在,嘗試以下方法:
test.prototype.anotherFn=function()
{
var self = this; // save reference to current scope
var p=new Promise(function(){
self.check(); // use self rather than this
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.