【发布时间】:2017-06-03 05:32:11
【问题描述】:
为什么Promise.then 在使用类方法作为回调时传递undefined 的执行上下文,而在使用“普通函数”时传递window?
类方法是否与其所属的对象/类分离?为什么是undefined 而不是window?
function normal() {
console.log('normal function', this);
}
const arrow = () => {
console.log('arrow function', this);
}
function strictFunction() {
'use strict';
console.log('strict function', this);
}
class Foo {
test() {
this.method(); // Foo
Promise.resolve().then(() => console.log('inline arrow function', this)); // Foo
Promise.resolve().then(normal); // window
Promise.resolve().then(arrow); // window
Promise.resolve().then(strictFunction); // undefined
Promise.resolve().then(this.method); // undefined <-- why?
}
method() {
console.log('method', this);
}
}
const F = new Foo();
F.test();
(jsFiddle)
我预计this.method 的上下文会丢失,但无法理解为什么this.method 与“正常”和箭头函数之间的行为不同。
这种行为有规范吗?我发现的唯一参考是 Promises A+,它指的是 “在严格模式下 this 内部将是 undefined;在草率模式下,它将是 global object。”。
【问题讨论】:
-
作为
obj.method传递的类方法引用总是与obj分离——这不是Promises 特定的。 -
@Alnitak 但为什么是
undefined而不是windowas expected (jsFiddle)? -
不确定 - 也许 ES6 类方法是隐式严格的?
-
classmethods are always strict mode。then不传递任何内容 (undefined) 作为上下文,其余的只是 usual behavior of thethiskeyword。
标签: javascript ecmascript-6 promise es6-promise