es6 装饰器

定义: 对类进行处理的函数。

示例1. 为Test类添加target成员foo, 值为'bar'

@fn
class Test {
}

function fn(target) {
   target.foo = 'bar';
}

console.log(Test.foo);

示例2. 为类添加target成员age, 其值通过传参控制

@fn2(20)
class Test {
}


function fn2(value){
     return function(target) {
        target.age = value;
    }
}

console.log(Test.age);

可以同时添加多个装饰器

@fn
@fn2(19)
class Test {
}

function fn(target) {
    target.foo = 'bar';
}

function fn2(value){
     return function(target) {
        target.age = value;
    }
}

示例3 为 类的实例 添加成员

@fn3
class Test {
}

function fn3 (target) {
    target.prototype.name = 'alex';
}

console.log(new Test().name)

实现mixin 

function mixin (...obj) {
    return function (target) {
        Object.assign(target.prototype, ...obj);
    }
}

const example = {
    tell () {
        console.log('this is in tell func');
    }
}

@mixin(example)
class MyClass{

}

new MyClass().tell()

示例4. 为类的成员变量添加装饰器

class Test {
    @readOnly sex = 'fale';
}


/**
 * 只读装饰器
 * @param {*} target 类的原型变量(prototype)
 * @param {*} name 类成员变量名
 * @param {*} descriptor 成员变量的修饰符
 */
function readOnly (target, name, descriptor) {
    descriptor.writable = false;
}

const test01 = new Test();
console.log(test01.sex);
test01.sex = 'female';    // 赋值会报错

成员变量装饰器也可用来装饰成员函数

class Test {
    @readOnly sex = 'male';

    @noenumeralbe sayTest () {
        console.log('hello test');
    }
}


function noenumerable(target, name, descriptor) {
  descriptor.enumerable = false;
}
const test01
= new Test(); // sayTest 不可迭代 for (let key in test01) { console.log(key, test01[key]); }
// 结果只会输出 sex male
// 可执行 test01.sayTest();

 

posted @ 2021-12-05 16:45  cecelia  阅读(435)  评论(0编辑  收藏  举报