重要的是要知道这个语法:
class A {
method = () => {}
}
只是在类构造函数中创建实例方法的语法糖:
class A {
constructor() {
this.method = () => {}
}
}
注意:此语法还不是 JavaScript 语言的正式部分(目前处于第 3 阶段),因此您必须使用像 Babel这样的转译器来处理它。
值this
内method
是一流的A
,因为这是this
在构造函数中指向(因为箭头的功能继承了它们在规定的范围内的情况下):
class A {
constructor() {
this.method = () => this;
}
}
const instance = new A();
console.log(instance.method() === instance); // true
在类上定义一个常规(非箭头函数)方法会在类原型(不是实例)上创建一个方法,但没有设置this
将是什么的规则(因为this
在 JS 中是动态的,取决于函数的调用方式,而不是它的调用方式定义)。
class A {
method() {}
}
console.log(new A().method === A.prototype.method); // true
如果在类实例上调用以这些方式中的任何一种定义的方法(通过.
),根据this
当函数作为对象的方法调用时如何绑定的规则,this
在两种情况下都将指向类实例:
class A {
constructor() {
this.methodOnInstance = () => this;
}
methodOnPrototype() { return this; }
}
const instance = new A();
console.log(
instance.methodOnInstance() === instance.methodOnPrototype(), // true
instance.methodOnPrototype() === instance // true
);
上面两个方法声明的一个主要区别是实例方法this
总是固定在类实例上,而类(原型)方法没有(我们可以通过使用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
被单击的元素或任何事件是)
对于所有(合成)DOM 事件处理程序,这也发生在 React 中。
因此,如果我们希望我们的方法的上下文始终指向 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
);