es7 class裝飾器

文檔http://es6.ruanyifeng.com/#docs/decorator

ts文檔 https://www.tslang.cn/docs/handbook/decorators.html#class-decorators

當多個裝飾器應用於一個聲明上,從上至下調用,從下而上執行html

interface InfoOpt {
  username: string;
  age: number;
  email: string;
}


function Info(opt: InfoOpt) {
  return function (target) {
    target.username = opt.username;
    target.age = opt.age;
    target.email = opt.email;
  }
}

@Info({
  username: 'ajanuw',
  age: 14,
  email: '123@sina.com'
})
class AJanuw {
  constructor() { }
}

console.log(
  AJanuw.username,
  AJanuw.age,
  AJanuw.email,
);

es 的裝飾器

let l = console.log

function klass(value) {
    return target => {
        // l(value) // api
        // l(target) // 對象
    }
}

function prop(value) {
    return function (target, key, des) { // target 對於靜態成員來講是類的構造函數,對於實例成員是類的原型對象
        // l(value) // username
        // l(target, key, des) // 對象,屬性名,屬性描述符
    }
}

function func(value) {
    return function (target, key, des) { // // target 對於靜態成員來講是類的構造函數,對於實例成員是類的原型對象
        // l(value) // function
        // l(key) // 函數名 show
        // l(des.value) // show函數, 能夠改寫
        // des.value = function(){
        //     l('hello')
        // }
    }
}

function Body(target) {
    // l( target ) // undefined
}

@klass('api')
class Ajanuw {
    @prop('username') name = 'ajanuw'

    @func('function')
    show(@Body body) {
        l(body)
    }
}

new Ajanuw().show()
相關文章
相關標籤/搜索