ES6 箭头回调如何确定 'this' 是什么?
How do ES6 arrow callbacks determine what 'this' is?
var test = {
literalLogger: function() {
console.log('literal')
console.log('this: ', this)
},
arrowLogger: () => {
console.log()
console.log('this: ', this)
},
nestedArrowLogger() {
this.arrowLogger();
}
}
第一个函数将 this 记录为对象。
第二个函数将其记录为 window。
第三个函数将其记录为 window.Why?
胖箭头函数捕获 this
关键字相对于它在它们声明的上下文中的内容(对于第二个 this
是 window)。
至于第三个,可能是因为对象字面量中的x()
是x: function()
的shorthand?
var test = {
literalLogger: function() {
console.log('literal')
console.log('this: ', this)
},
arrowLogger: () => {
console.log()
console.log('this: ', this)
},
nestedArrowLogger() {
this.arrowLogger();
}
}
第一个函数将 this 记录为对象。 第二个函数将其记录为 window。 第三个函数将其记录为 window.Why?
胖箭头函数捕获 this
关键字相对于它在它们声明的上下文中的内容(对于第二个 this
是 window)。
至于第三个,可能是因为对象字面量中的x()
是x: function()
的shorthand?