) {
console.log('calling');
习题:理解装饰者模式,计算下面结果
装饰者模式在不改变对象本身的情况下,在程序运行阶段为对象动态增加功能。
ES6 开始用 @
标识装饰器,即 @decorator
,题目中的类 animalDecorator
是一个类装饰器,类装饰器会在运行时当作函数被调用,类的构造函数将作为其唯一的参数。
装饰器中使用了泛型相关知识 <>
(我们将在泛型章节详细介绍)。
为了更好的理解装饰器,我们看看 tsc
编译后的核心代码
const animalDecorator = (constructor) => {
return class extends constructor {
constructor() {
super(...arguments);
this.age = 20;
let Animal = class Animal {
constructor(age) {
this.age = age;
Animal = __decorate([
animalDecorator
], Animal);
new Animal(10).age;
类装饰器 animalDecorator
返回了一个匿名类,记做匿名类 A
下面简称类 A
。类 A
继承于类 Animal
的构造函数。运行时候会先执行类 Animal
的构造函数,在执行类 A
的构造函数,这样也就达到了装饰器的目的。所以答案为 20
。