了解以下语法很重要:
class A {
method = () => {}
}
只是在类构造函数中创建实例方法的语法糖:
class A {
constructor() {
this.method = () => {}
}
}
注意:此语法还不是 JavaScript 语言的官方部分 (currently in stage 3),因此您必须使用 transpiler like Babel to handle it。
method 中this 的值是A 类,因为这是this 在构造函数中指向的内容(因为arrow functions 从定义它们的范围继承上下文):
class A {
constructor() {
this.method = () => this;
}
}
const instance = new A();
console.log(instance.method() === instance); // true
在类上定义一个常规(非箭头函数)方法会在类原型(不是实例)上创建一个方法,但没有设置 this 将是什么规则(因为 this 在 JS 中是动态的,@987654324 @)。
class A {
method() {}
}
console.log(new A().method === A.prototype.method); // true
如果在类实例上调用以这两种方式中的任何一种定义的方法(通过.),根据当函数作为对象的方法调用时this 的绑定规则,@987654341 @ 在这两种情况下都会指向类实例:
class A {
constructor() {
this.methodOnInstance = () => this;
}
methodOnPrototype() { return this; }
}
const instance = new A();
console.log(
instance.methodOnInstance() === instance.methodOnPrototype(), // true
instance.methodOnPrototype() === instance // true
);
上面两个方法声明的一个主要区别是实例方法有thisalways固定到类实例,而类(原型)方法没有(我们可以通过使用Function.prototype.apply 或 Function.prototype.call)
class A {
constructor() {
this.methodOnInstance = () => this;
}
methodOnPrototype() { return this; }
}
const instance = new A();
console.log(
instance.methodOnInstance() === instance.methodOnPrototype(), // true
instance.methodOnPrototype.call('new this') === 'new this' // true
);
this 更改的常见情况是在事件处理程序中,其中事件处理程序调用传递给它的函数并将上下文绑定到发生事件的元素(因此将 this 的值覆盖为是被点击的元素或任何事件)
这在 React 中也发生在所有 (synthetic) DOM 事件处理程序中。
因此,如果我们希望方法的上下文始终指向 React 组件的实例,我们可以使用实例方法。
另一种限制上下文但不使用需要 Babel 的特殊实例方法语法的方法是,通过使用绑定上下文的类(原型)方法创建一个新函数(使用Function.prototype.bind),直接自己创建一个实例方法:
class A {
constructor() {
this.methodOnInstance = this.methodOnPrototype.bind(this);
}
methodOnPrototype() { return this; }
}
const instance = new A();
console.log(
instance.methodOnInstance() === instance.methodOnPrototype(), // true
instance.methodOnPrototype() === instance // true
);
这使我们能够获得与使用特殊实例方法语法相同的结果,但使用当前可用的工具(ES2017 及以下)。
如果出于某种原因我们想要一个始终绑定到非类实例的方法,我们也可以这样做:
class A {
constructor() {
this.method = this.method.bind(console);
}
method() { return this; }
}
const instance = new A();
console.log(
instance.method() === console // true
);