简体   繁体   English

Typescript 属性装饰器 - 需要帮助了解以下情况如何发生?

[英]Typescript property decorator - Need help to understand how the following happens?

I was just experimenting with Typescript property decorators.我只是在试验 Typescript 属性装饰器。 But, I could not understand the behavior of the following code:但是,我无法理解以下代码的行为:

function dec(hasRole: boolean) {
    return function (target: any, propertyName: string) {
        let val = target[propertyName];
        Object.defineProperty(target, propertyName, {
            get() { return val; },
            set(value) { val = hasRole; }
        });
    }
}

class Hey {
    age: number;

    @dec(true)
    hasRole: boolean = false;

    constructor(age: number) {
        this.age = age;
    }
}

let ob = new Hey(22);
console.log(ob);

//Actual Output: //实际Output:

age: 22
hasRole: true
__proto__:
  constructor: class Hey
  hasRole: true
  get hasRole: ƒ get()
  set hasRole: ƒ set(value)
  __proto__: Object

The result I expected was: 1. OwnProperty -> hasRole = false 2. Prototype property -> hasRole = true.我预期的结果是: 1. OwnProperty -> hasRole = false 2. Prototype property -> hasRole = true。 As 'target' in decorator argument provides the constructor function for static members or prototype of the class for instance members.作为装饰器参数中的“目标”,为 static 成员提供构造函数 function 或为实例成员提供 class 的原型。

Could someone explain me this functionality?有人可以解释一下这个功能吗?

In order to understand it clearly you should take a look at the transpiled version为了清楚地理解它,你应该看看转译的版本

function dec(hasRole) {
    return function (target, propertyName) {
        let val = target[propertyName];
        Object.defineProperty(target, propertyName, {
            get() { return val; },
            set(value) { val = hasRole; }
        });
    };
}
class Hey {
    constructor(age) {
        this.hasRole = false;
        this.age = age;
    }
}
__decorate([
    dec(true)
], Hey.prototype, "hasRole", void 0);
let ob = new Hey(22);
console.log(ob);

From the code above it should be clear that class is decorated first and only then a new instance is created从上面的代码可以清楚地看出,首先装饰了 class,然后才创建了一个新实例

It means that at the time constructor is being executed hasRole is already defined in Prototype hence assigning this.hasRole to anything doesn't have any effect: it's always assigned to hasRole parameter in decorator(which is true )这意味着在执行构造函数时hasRole已经在 Prototype 中定义,因此将this.hasRole分配给任何东西都没有任何效果:它总是分配给装饰器中的hasRole参数(这是true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM