在 Angular 中,技术上可以将类方法编写为 ES2015 箭头函数,但我从未真正看到有人这样做过。以这个简单的组件为例:
@Component({
selector: 'sample'
})
export class SampleComponent {
arrowFunction = param => {
// Do something
};
normalFunction(param) {
// Do something
}
}
这没有任何问题。有什么不同吗?为什么我应该或不应该使用它?
最佳答案
在 this React answer 中提出的要点在 Angular、任何其他框架或普通 JavaScript/TypeScript 中仍然有效。
类原型(prototype)方法是 ES6,类箭头方法不是。箭头方法属于 class fields proposal而不是现有规范的一部分。它们是用 TypeScript 实现的,也可以用 Babel 进行转换。
通常最好使用原型(prototype) method() { ... }
而不是箭头 method = () => { ... }
因为它更灵活。
回调
箭头方法提供的唯一真正机会是它可以无缝地用作回调:
class Class {
method = () => { ... }
}
registerCallback(new Class().method);
如果原型(prototype)方法应该用作回调,则应该额外绑定(bind)它,最好在构造函数中完成:
class Class {
constructor() {
this.method = this.method.bind(this);
}
method() { ... }
}
registerCallback(new Class().method);
像bind-decorator
这样的装饰器可以在 TypeScript 和 ES Next 中使用,为构造函数中的方法绑定(bind)提供更简洁的替代方法:
import bind from 'bind-decorator';
class Class {
@bind
method() { ... }
}
继承
箭头方法限制子类也使用箭头方法,否则它们不会被覆盖。如果忽略了箭头,则会产生问题:
class Parent {
method = () => { ... }
}
class Child extends Parent {
method() { ... } // won't override Parent method
}
不可能在子类中使用super.method()
,因为super.method
引用了Parent.prototype.method
,它不存在:
class Parent {
method = () => { ... }
}
class Child extends Parent {
method = () => {
super.method(); // won't work
...
}
}
混合
原型(prototype)方法可以有效地用于混入。 Mixin 对于多重继承或修复 TypeScript 方法可见性方面的问题很有用。
由于箭头方法在类原型(prototype)上不可用,因此无法从类外部访问它:
class Parent {
method = () => { ... }
}
class Child extends OtherParent { ... }
Object.assign(Child.prototype, Parent.prototype) // method won't be copied
测试
原型(prototype)方法提供的一个有值(value)的特性是它们在类实例化之前是可访问的,因此它们可以在测试中被窥探或模拟,即使它们在构造后立即被调用也是如此:
class Class {
constructor(arg) {
this.init(arg);
}
init(arg) { ... }
}
spyOn(Class.prototype, 'init').and.callThrough();
const object = new Class(1);
expect(object.init).toHaveBeenCalledWith(1);
当方法是箭头时这是不可能的。
TL;DR:原型(prototype)和箭头类方法之间的选择似乎是一种品味问题,但实际上原型(prototype)方法的使用更具远见。您通常可能希望避免使用箭头类方法,除非您确定它们不会造成不便。如果您将它们作为回调传递,请不要忘记在原型(prototype)方法上使用 bind
。
关于angular - 我应该在 Angular 的类中将方法写成箭头函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45881670/