es5-decorator

0.0.1 • Public • Published

ES5 Decorator

===============================

This package provides an compatible decorator maker with ES7 Decorators.

Installation

npm install es5-decorator

Examples

decorate(type, [args,] obj, key);

autobind

var decorator = require('../src/decorator.js');
 
function autobind(target, key, descriptor){
  var fn = target[key];
  target[key] = function(){
    return fn.apply(target, arguments);
  }
  return target[key];
}
 
var Point = function(x, y){
  this.x = x;
  this.y = y;
};
Point.prototype.length = function(){
  return Math.sqrt(this.x * this.x + this.y * this.y);
}
 
var p = new Point(1, 1);
var len = decorator(autobind, p, 'length');
console.log(len()); //1.414213562

deprecate

function deprecate(target, key, descriptor){
  if(typeof target !== 'string'){
    console.log('[Function ' + key + '] has been deprecated.');
    return target[key];
  }else{
    console.log(target);
    return function(){};
  }
}
 
var myObj = {
  test: function(){
    return 'hello world';
  }
}
decorator(deprecate, myObj, 'test');
 
console.log(myObj.test());

decorate(type, [args,] obj);

doge & animal

function doge(target){
  target.isDoge = true;
}
 
function animal(target){
  target.isAnimal = true;
}
 
var Dog = function(){
 
}
 
decorator(doge, Dog.prototype);
decorator(animal, Dog.prototype);
  
var dog = new Dog();
 
console.log(dog.isDoge && dog.isAnimal);

decorate(type, [args,] obj=null, func);

multicast

function multicast(target, key){
  var fn = target[key];
 
  target[key] = function(){
    var list = arguments[0];
    if(!Array.isArray(list)){
      return fn.apply(this, arguments);
    }else{
      var ret = [];
      var args = [].slice.call(arguments);
      for(var i = 0; i < list.length; i++){
          args[0] = list[i];
          ret.push(fn.apply(this, args));                    
      }
      return ret;
    }
  }
 
  return target[key];
}
 
function inc(x, y){return x + y};
inc = decorator(multicast, null, inc);
 
console.log(inc([1,2,3,4], 1); //2,3,4,5

Test cases

npm run test

Readme

Keywords

Package Sidebar

Install

npm i es5-decorator

Weekly Downloads

1

Version

0.0.1

License

MIT

Last publish

Collaborators

  • akira_cn