Home  >  Article  >  Web Front-end  >  Detailed introduction to Decorator in ES6

Detailed introduction to Decorator in ES6

零下一度
零下一度Original
2017-06-24 14:44:521474browse

Decorator means decorator

1. Concept

A decorator is a function used to modify a class Behavior (Note: 1. Function 2. Modify behavior 3. Operate class)

1. Read-only modifier

{
  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());
}

 You can also modify it in front of the class

{
  let typename=function(target,name,descriptor){
    target.myname='hello';
  }

  @typename
  class Test{

  }

  console.log('类修饰符',Test.myname);//hello  // 第三方库修饰器的js库:core-decorators; npm install core-decorators}

 

{
  let log=(type)=>{return function(target,name,descriptor){
      let src_method=descriptor.value;
      descriptor.value=(...arg)=>{
        src_method.apply(target,arg);
        console.info(`log ${type}`);
      }
    }
  }

  class AD{
    @log('show')
    show(){
      console.info('ad is show')
    }
    @log('click')
    click(){
      console.info('ad is click');
    }
  }

  let ad=new AD();
  ad.show();
  ad.click();
}

The above is the detailed content of Detailed introduction to Decorator in ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn