簡體   English   中英

將箭頭功能包裝在普通功能內

[英]Wrapping an arrow function inside a normal function

我的目標是我試圖將此上下文從普通函數傳遞到箭頭函數,但我一直無法定義。

我知道, 在一個正常的功能和動態行為來確定該函數是怎么被調用。 箭頭函數中的this遵循詞法作用域規則來確定其值。 但是,當我在第16行調用printWrapper()時, 被設置為car對象,因此,當我進一步調用printThis()時,按照詞法作用域規則,它應該打印car對象,但在我的情況下, 對象在第2行上打印的是全局對象。

printThis = () => {
  console.log(this); // prints the global object
}

var car = {
  year: 2015,
  printThis: printThis,
  printWrapper: printWrapper
}

function printWrapper() {
  console.log(this); // prints the car object
  printThis();
}

car.printWrapper();

如評論中所述,箭頭函數的上下文與定義它的范圍的上下文相同,而不是調用它的上下文。

如果需要將此上下文“傳遞給函數”,則可以使用Function.prototype.bind() ,它將返回一個新函數,該函數將第一個傳遞的參數分配給this Function.prototype.call()Function.prototype.apply()工作原理類似,即使用所需this調用該函數。

請注意,此方法僅適用於正常功能。 箭頭函數是匿名的,無法明確設置其上下文。

 function printThis() { console.log(this); // prints the car object } var car = { year: 2015, printThis: printThis, printWrapper: printWrapper } function printWrapper() { console.log(this); // prints the car object printThis.call(this); } car.printWrapper(); 

所以我用了詞匯和動態作用域和假設printThis()將能夠訪問printWrapper的這個 ()。 提到詞法作用域的工作原理相對於該代碼的靜態結構,這意味着移動printThis內部printWrapper()函數()將允許它自己的是從printThis訪問()。

var car = {
  year: 2015,
  printWrapper: printWrapper
}

function printWrapper() {
  console.log(this); // prints the car object
  printThis = () => {
    console.log(this); // also prints the car object, *this* now refers to the scope of printwrapper
  }
  printThis();
}

car.printWrapper();

暫無
暫無

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

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