zoukankan      html  css  js  c++  java
  • 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';
    
        @noemunalbe sayTest () {
            console.log('hello test');
        }
    }
    
    
    const test01 = new Test();
    
    // sayTest 不可迭代
    for (let key in test01) {
        console.log(key, test01[key]);
    }
    
    // 可执行
    test01.sayTest();
  • 相关阅读:
    html中的块级元素、行内元素
    ptyhon_opencv 图像的基本操作
    正则表达式总结 2017.1.6
    HashMap 中的 entrySet()使用方法 2016.12.28
    (转)Redis持久化的几种方式
    负数与二进制换转方法
    (转)2019JAVA面试题附答案(长期更新)
    Java后端技术面试汇总(第一套)
    (转)Dubbo服务暴露过程源码分析
    Dubbo消费方服务调用过程源码分析
  • 原文地址:https://www.cnblogs.com/ceceliahappycoding/p/15646063.html
Copyright © 2011-2022 走看看