js的装饰符 @

原文地址:https://www.jeremyjone.com/666/, 转载请注明。


js中的装饰器一直处于提案阶段,所以要是用装饰符@,就需要通过babel进行解析。

安装babel的插件

如果 babel < 7.x:

1、安装npm install --save-dev babel-plugin-transform-decorators-legacy
2、在.babelrc文件中添加:

{
    "plugins": ["transform-decorators-legacy]
}
如果babel >= 7.x:

1、安装npm install --save-dev @babel/plugin-proposal-decorators
2、在.babelrc文件中添加:

{
    "plugins": [
        ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ]
}
注意顺序:

如果插件中添加了transform-class-properties,需要保证它在装饰器插件的后面。

装饰符的使用

要理解一个装饰器,可以通过下面这个小例子:

class Circle {
    draw() {
        console.log("画一个圆");
    }
}

class Decorator {
    constructor(circle) {
        this.circle = circle;
    }

    draw() {
        this.circle.draw();
        this.setRedBorder(this.circle);
    }

    setRedBorder(circle) {
        console.log("设置红色边框");
    }
}

// 测试
let c = new Circle();
c.draw();

let d = new Decorator(c);
d.draw();

可以看到通过装饰器方式,可以画出一个带红色边框的圆。

理解了装饰器,装饰符就大体可以理解了。

// 定义装饰器函数,该方法可以接收装饰符传递的参数
function log(type) {
    // 这是装饰符对应函数的标准接口函数。其中:target是作用的实例;name是作用的函数名;descriptor是一个标准装饰器对象,其中value是对应作用的函数。
    return function(target, name, descriptor) {
        let oldValue = descriptor.value;

        descriptor.value = function() {
            // 打印日志
            console.log(`打印日志:类型为 - ${type}`);
            // 执行原有方法
            return oldValue.apply(this, arguments);
        };

        return descriptor;
    }
}

// 使用方法
class A {
    @log("text")
    testFunc() {
        console.log("函数方法");
    }
}

let a = new A();
a.testFunc();

执行结果如下:
file

更多关于装饰符@的内容,可以看提案地址:https://github.com/tc39/proposal-decorators

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章