簡體   English   中英

ES6 Javascript:使用箭頭函數從類中調用靜態方法

[英]ES6 Javascript: Calling static methods from classes with arrow functions

雖然這按預期工作

class ClassWithStaticMethod {

  static staticMethod() {
    return ('staticMethod');
  };

  static staticMethod2() {
    const yee = this.staticMethod();
    return 'staticMethod2 '+yee;
  };

}

console.log(ClassWithStaticMethod.staticMethod2());
//staticMethod2 staticMethod

這是,

i)可以使用類名訪問staticMethod(),並且

ii)該方法可以使用“ this ”調用同一類中的另一個靜態方法,

這不行

class ClassWithStaticMethod {

  static staticMethod = () => {
    return ('staticMethod');
  };

  static staticMethod2 = () => {
    const yee = this.staticMethod;
    return 'staticMethod2 '+yee;
  };

}

console.log(ClassWithStaticMethod.staticMethod2());
//staticMethod2 undefined

從某種意義上說,我仍然可以訪問staticMethod()方法,但無法訪問第一個方法中的另一個方法。 我不確定,如果我使用

    const yee = this.staticMethod();

我得到一個錯誤

錯誤TypeError:_this.staticMethod不是函數

箭功能繼承this從外范圍,而不是他們的this取決於它們的調用上下文。 由於staticMethod2嘗試訪問this.staticMethod ,因此僅當this引用ClassWithStaticMethod -也就是說,如果staticMethod2標准函數 ,而不是箭頭函數。

您還需要調用 this.staticMethod() const yee = this.staticMethod;將導致將staticMethod強制轉換為字符串,而不是被調用)

更改這兩個問題,它將按預期工作:

 class ClassWithStaticMethod { static staticMethod = () => { return ('staticMethod'); }; static staticMethod2 = function() { const yee = this.staticMethod(); return 'staticMethod2 '+yee; }; } console.log(ClassWithStaticMethod.staticMethod2()); 

在通用方面,這是一個帶有箭頭功能的怪癖:他們this具有通用范圍。 (這就是為什么您要使用更好的調用堆棧就必須使用function()的原因)。 在第二種方法中, this是指調用上下文: window

如以下注釋中所述,為方便起見,請勿使用簡寫語法。 我們有這么多選擇是有原因的。

要修復它,您可以只使用function()定義第二個函數; ()在對象的情況下。

但是,這將起作用:

class ClassWithStaticMethod2 {

  static staticMethod = () => {
    return ('staticMethod');
  };

  static staticMethod2 = function() {
    console.log(this)
    const yee = this.staticMethod();
    return 'staticMethod2 '+yee;
  };

}

在這里查看

暫無
暫無

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

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