Web端 es6(基础十五) Decorators

装饰器

推荐第三方修饰器

core-decorators

//npm 安装
nom install core-decorators

设置只读

// 修饰为只读
let readonly = function (target,name,descriptor) {
    descriptor.writable = false;
    return descriptor;
};

class Test{
    @readonly
    time(){
        return '2017-03-11'
    }
}

let test = new Test();
/* 这里代码会 出错,因为是只读的 
test.time = function () {
    console.log('reset time')
};*/
console.log(test.time());

附加静态

//类修饰
let  typename = function (target, name, descriptor) {
   target.PI = 3.1415926;
};

@typename
class Test{

}
console.log(`类修饰的值:${Test.PI}`)
// 输出结果
类修饰的值:3.1415926

小案例 埋点

let log = (type) => {
    return function (target, name, descriptor) {
        // 获取方法
        let src_method = descriptor.value;
        descriptor.value = (...arg) => {
            src_method.apply(target, arg);
            console.info(`log ${type} 参数:${arg}`);
        }
    }
};

class AD{
    @log('show')
    show(message){
        console.info(`ad is show ${message}`)
    }

    @log('click')
    click(){
        console.info('ad is click')
    }
}

let ad = new AD();
ad.show('he;;');
ad.click();
// 输出结果
ad is show he;;
log show 参数:he;;
ad is click
log click 参数:

你可能感兴趣的:(Web)