JavaScript:了解回调函数的执行上下文

时间:2019-06-23 13:28:31

标签: javascript this

const button = document.querySelector('button');

button.addEventListener('click', () => {
  console.log('From click listener - arrow function:', this);
});
button.addEventListener('click', function () {
  console.log('From click listener - normal function:', this);
});
Promise.resolve().then(function () { 
  console.log('From Promise - normal function:', this);
});
Promise.resolve().then(() => { 
  console.log('From Promise - arrow function:', this);
});
setTimeout(function () {
  console.log('From setTimeout - normal function:', this);
});
setTimeout(() => {
  console.log('From setTimeout - arrow function:', this);
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<button>Click me!</button>
</body>
</html>

请查看上面的代码段。我想了解在以上每种情况下如何推断this。通常,如何推断this在回调函数中(例如,传递给window.setTimeoutPromise.thenHTMLElement.addEventListener的回调)。

1 个答案:

答案 0 :(得分:0)

如果要编写箭头函数,则将从外部继承this。如果您要编写“正常”函数,则将创建一个this的新上下文。

window.setTimeout还是其他承诺都没关系。

例如:

this.value = 2
const example = {
  value: 1,
  arrowFunction: () => this.value,
  normalFunction: function () { return this.value },
}

console.log(example.arrowFunction()) // will print 2
console.log(example.normalFunction()) // will return 1

您可以在此处了解更多信息:https://www.quora.com/What-does-this-in-JavaScript-mean/answer/Quildreen-Motta