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

 

猜你喜欢

转载自www.cnblogs.com/sunmarvell/p/9149847.html