decorator

package.json

{
  "name": "decorator-test",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack --config=webpack.dev.js",
    "start": "node ./dist/test.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "devDependencies": {
    "@babel/core": "^7.9.6",
    "@babel/plugin-proposal-decorators": "^7.8.3",
    "@babel/preset-env": "^7.9.6",
    "babel-loader": "^8.1.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.5",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  }
}

code

@transform
class IronMan {
    // ...
}

function transform(target) {
    target.weapon = "laser"
}

console.log(IronMan.weapon) // laser

class Person {
    constructor(first, last) {
        this.first = first
        this.last = last
    }

    @readonly
    @log
    name() { return `${this.first} ${this.last}` }
}

function readonly(target, name, descriptor) {
    console.log('readonly toggled')
    descriptor.writable = false
    return descriptor
}

function log(target, name, descriptor) {
    console.log('log toggled')
    console.log(target + '\n', name + '\n', descriptor.value + '\n')
    let method = descriptor.value
    descriptor.value = function(args) {
        console.log("log监听开始:", name)
        let res = method.apply(this, args)
        console.log("log监听结束:", name)
        return res
    }
    return descriptor
}
const person = new Person("x", "j")
// person.name()
console.log(person.name())
// console.log(person.name = 1)
// console.log(person.name)

github 地址:
https://github.com/JasonXiang2014/jsDecorator

你可能感兴趣的:(decorator)