node 使用类的修饰符(decorator)

1. 安装 @babel 依赖

npm i -D @babel/core @babel/node
npm i -D @babel/preset-env @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties

  

2. 配置 .babelrc

{
  "presets": ["@babel/preset-env"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
}

3. 编写案例  decorate.js

const rules = {
    name: 'string',
    password: 'string',
    age: 'number'
}

const validator = rules => targetClass => new Proxy(targetClass, {
    construct(target, args) {
        const obj = new target(...args)
        for (let [name, type] of Object.entries(rules)) {
            if (typeof obj[name] !== type) {
                throw new Error(`${name} must be ${type}`)
            }
        }
        return obj
    },
    get(target, property) {
        return `${property}: ${target[property]}`
    }
})

const toString = attrs => (target, property, descriptor) => {
    descriptor.value = function () {
        return attrs.map(attr => `${attr}: ${this[attr]}`).join(', ')
    }
    return descriptor
}

const log = (target, property, descriptor) => {
    const oldValue = descriptor.value
    descriptor.value = function () {
        const result = oldValue.apply(this, arguments)
        console.log(`Calling ${property} with`, ...arguments)
        console.log(`Return ${result}`)
        return result
    }
    return descriptor
}

@validator(rules)
class Person {
    static constVal = '1'
    constructor({ name, password, age }) {
        this.name = name
        this.password = password
        this.age = age
    }

    @toString(['name', 'password', 'age'])
    toString() { }

    @log
    setAge(age) {
        this.age = age
    }

    @log
    getAge() {
        return this.age
    }
}

const person = new Person({
    name: 'lutz',
    password: '123',
    age: 18
})
// console.log(Person.constVal)
// console.log(Person.toString)

// console.log(person.toString())
person.setAge(19)
person.getAge()

5. 测试

npx babel-node decorate.js

 

6. 效果

 

posted @ 2020-10-13 14:14  .K_o  阅读(432)  评论(0)    收藏  举报