簡體   English   中英

這兩個ES6功能如何不同地訪問“ this”?

[英]How do these two ES6 functions access “this” differently?

我很好奇,為什么functionA返回錯誤,而functionB具有對“ this”的正確引用並起作用。 差異的原因是什么?

class MyComponent extends Component {
  ...

  render() {
    return (
      <input ref="myInput" type="text" />
      <button onClick={this.functionA} />
      <button onClick={this.functionB} />
    );
  }
}

這將引發錯誤“無法讀取未定義的屬性'refs':

functionA() {
  const val = this.refs.myInput.value;
  console.log(val); 
}

盡管這正確顯示了值:

functionB = () => {
  const val = this.refs.myInput.value;
  console.log(val); 
}

這兩個函數之間的區別是使用了在es6上添加的arrow表達式,該表達式允許使用lexycal this。

在使用箭頭函數之前,每個新函數都定義了自己的this值,從而阻止您訪問正確的值。 常見的解決方法之一是在正確的上下文級別定義對此的引用,並在函數中使用它:

var that = this; //creating a reference to the this we will need in a function
that.refs.myInput.value; // in our function we refer to 'that' variable

箭頭函數會捕獲封閉上下文的this值,因此您在FunctionB中引用的this實際上是從“正確”上下文中獲取的。

有關更多信息,請檢查: https : //developer.mozilla.org/it/docs/Web/JavaScript/Reference/Functions/Arrow_functions

在JavaScript函數上下文是在調用函數時定義的,而不是在定義函數時定義的。

您將兩個函數都作為回調傳遞給其他組件。 它們在定義的對象之外被稱為。 因此,他們不共享它的類上下文。

在這里與眾不同的是functionB定義。 使用箭頭功能可將當前上下文綁定到基礎功能。

您可以在此處閱讀更多信息http://reactkungfu.com/2015/07/why-and-how-to-bind-methods-in-your-react-component-classes/ ...或如果您有興趣,可以在google上閱讀更多內容。

在傳統的函數聲明即function關鍵字this內部函數范圍是指以該函數所屬的對象,或undefined如果沒有托管對象.The點是function形成從外部不同的新的范圍

在new =>語法中,存在一個不同的故事。該函數不是來自新作用域(與舊方法完全不同),而是其作用域與外部作用域相同

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

暫無
暫無

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

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