zoukankan      html  css  js  c++  java
  • es6之Decorator

    修饰器

    是一个函数,用来修改 类的行为

    {
      let readonly=function(target,name,descriptor){
        descriptor.writable=false;
        return descriptor
      };
    
      class Test{
        @readonly
        time(){
          return '2017-03-11'
        }
      }
    
      let test=new Test();
    
      // test.time=function(){
      //   console.log('reset time');
      // };    //报错
    
      console.log(test.time());
    }

    基本上,修饰器的行为就是下面这样。

    @decorator
    class A {}
    
    // 等同于
    class A {}
    A = decorator(A) || A;

    下面是另一个例子,修改属性描述对象的enumerable属性,使得该属性不可遍历。

    class Person {
      @nonenumerable
      get kidCount() { return this.children.length; }
    }
    
    function nonenumerable(target, name, descriptor) {
      descriptor.enumerable = false;
      return descriptor;
    }
     
    {
      let typename=function(target,name,descriptor){
        target.myname='hello';
      }
    
      @typename
      class Test{
    
      }
    
      console.log(Test.myname);     //hello
    }

    core-decorators.js

    core-decorators.js是一个第三方模块,提供了几个常见的修饰器,通过它可以更好地理解修饰器。

      第三方库修饰器的js库:core-decorators;通过js文件引入,

    或者npm install core-decorators

     
  • 相关阅读:
    缓存(二)
    缓存
    SQL Server 导入大数据脚本
    C#执行OracleHelper
    MERGE 用法
    c# 高效读写文件
    C#网络编程
    C#常用IO流与读写文件
    注册asp.net 4.0 到iis
    javascript原生图片懒加载
  • 原文地址:https://www.cnblogs.com/sunmarvell/p/9149847.html
Copyright © 2011-2022 走看看