Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6+:装饰器原理 #5

Open
Chenjiayuan195 opened this issue May 20, 2020 · 1 comment
Open

ES6+:装饰器原理 #5

Chenjiayuan195 opened this issue May 20, 2020 · 1 comment

Comments

@Chenjiayuan195
Copy link
Owner

No description provided.

@Chenjiayuan195
Copy link
Owner Author

作用于类的装饰器:其实就是将当前类作为参数传入装饰器函数
作用于类属性的装饰器:调用了Object.defineProperty,如下例子

class Dog {
    @extendsArgs
    say() {
        console.log("hello");
    }
}
function extendsArgs(target,name,descriptor){
  target.name = 'Tom',
 discriptor.writable = false;
}

let Tom = new Dog();
// Tom.name = 'Tom'

Tom.say = function() {
    console.log("woof !");
}
Tom.say() // 'hello'

所以作为类属性的时候实际是如下

let descriptor = {
    value: function() {
        console.log("hello");
    },
    enumerable: false,
    configurable: true,
    writable: true
};

descriptor = readonly(Dog.prototype, "say", descriptor) || descriptor;

Object.defineProperty(Dog.prototype, "say", descriptor);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant