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();
  • 相关阅读:
    Java内部类
    sql几种连接的区别
    常见的十大算法
    使用yml文件配置数据库数据时的问题
    SpringBoot整合Mybatis
    不是书评 :《我是一只IT小小鸟》
    考试考完了·
    MSSQL站库分离情况的渗透思路
    VENOM cve-2015-3456 Qemu 虚拟机逃逸漏洞POC
    Python 实现指定目录下 删除指定大小的文件
  • 原文地址:https://www.cnblogs.com/ceceliahappycoding/p/15646063.html
Copyright © 2011-2022 走看看