Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

箭头函数this?

var obj = {
  a: 10,
  b: () => {
    console.log(this.a); // undefined
    console.log(this); // Window {postMessage: ?, blur: ?, focus: ?, close: ?, frames: Window, …}
  }
}

MDN中阐述:在箭头函数中,this与封闭词法环境的this保持一致。在全局代码中,它将被设置为全局对象

想问下封闭词法环境到底是什么环境?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

MDN里不是有附例子说明吗?
意思就是在箭头函数中的this和箭头函数外的this是一致的。而且是绑定的,不受bind/call/apply干扰的
比如说

var _this = this;
var obj = {
  name: 'obj',
  b: () => {
    // 这里的 this 同 obj 所处作用域的this是一致的 即 this === _this
    console.log(this === _this)
  }
}
obj.b() // true
obj.b.bind({x: 1})() // true
obj.b.call({y: 2}) // true

如果你的箭头函数的外层还是一个箭头函数的函数体那么继续往上查找this,直到全局作用域即最外层this既window【严格模式为undefined】。有点在作用域链中查找变量的感觉。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...