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();
  • 相关阅读:
    React 之使用 fetch
    react-native 环境搭建
    create-react-app 配置 less
    React新的前端思维方式
    字体图标 —— IconMoon
    你不知道的javascript 之 >>
    前端的自我修养
    jquery 学习
    html的meta总结
    git基本操作 nginx基本操作
  • 原文地址:https://www.cnblogs.com/ceceliahappycoding/p/15646063.html
Copyright © 2011-2022 走看看