簡體   English   中英

無法從Javascript中的另一個方法內部調用一個方法

[英]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();

隨后的范圍將綁定到“類型” testt實例。 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.

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