类里的属性是实例属性啊, 为什么装饰器里要传递targetclassPrototype
来源:11-18 【属性装饰器】属性装饰器应用,JS源码深剖

crazyones110
2021-10-07
// 2. 属性装饰器
function loginProperty(attrValue) {
return function (targetclassPrototype, attrname) {
console.log("targetclassPrototype:", targetclassPrototype);
console.log("attrname:", attrname);
targetclassPrototype.constructor.custLevelDescri = function () {
console.log("消费5000元升级为贵宾");
console.log("消费10000元升级为贵宾,赠送微波炉一个");
};
};
}
// 3.目标类
var CustomerService = /** @class */ (function () {
function CustomerService() {
this.custname = "王五";
}
CustomerService.prototype.show = function () {
console.log("顾客名:", this.custname);
};
__decorate([
loginProperty("顾客登记")
], CustomerService.prototype, "degree");
return CustomerService;
}());
CustomerService.custLevelDescri();
上面贴的是课件里的源码, 只有实例化一个类的时候才能操作属性呀, 上面的装饰器仅仅是在类上加了一个静态方法, 和属性完全不沾边呀
而且讲道理属性装饰器传递targetClass不是比targetClassPrototype更方便吗, TS这么设计是有什么考量吗
写回答
1回答
-
keviny79
2021-10-07
属性和属性装饰器的意义要分开, TS 设计 属性装饰器 设计的主要目的 并不是为了获得属性的值,或者对属性的值进行什么操作 【实际上 绝大多数场景并不需要获取属性的值】, TS 设计 属性装饰器 设计的目的 是为了能实现 “依赖注入”,外部可以再不创建对象的情况下为属性 分配一个对象(注入) ,这一点本章10-31 后有详尽的讲解,所以传递一个原型参数给属性装饰器反而 更加好,因为原型可以获取到的对象更多,防止偶尔用到。
这里静态方法只是一个属性装饰器的测试例子,不必理会,真正的 仿 Nestjs 实战中有属性装饰器的应用场景
122021-10-07
相似问题