将箭头功能包装在普通功能内

时间:2019-09-03 20:54:08

标签: javascript this arrow-functions

我的目标是我试图将 this 上下文从普通函数传递到箭头函数,但我一直不确定。

我知道普通函数中的 this 行为动态,并由函数调用方式决定。箭头函数中的 this 遵循词汇作用域规则来确定其值。但是,当我在第16行调用printWrapper()时, this 设置为car对象,因此,当我进一步调用printThis()时,按照词法作用域规则,它应该打印car对象,但在我的情况下,第2行上打印的 this 对象是全局对象。

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();

2 个答案:

答案 0 :(得分:0)

如评论中所述,箭头函数的上下文与定义范围的上下文相同,而不是调用它的上下文。

如果您需要将 this 上下文“传递”给可以使用Function.prototype.bind()的函数,它将返回一个新函数,并将第一个传递的参数分配给thisFunction.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();

答案 1 :(得分:0)

因此,我混合了词法作用域和动态作用域,并假定printThis()将能够访问printWrapper()的 this 。正如Pointy所提到的,词法作用域针对代码的静态结构起作用,这意味着在printWrapper()中移动printThis()函数将允许从printThis访问其自己的 this ()。

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();
相关问题