es5-decorator
v0.0.1 decorator
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
npm i es5-decorator
Metadata
- MIT
- Whatever
- [email protected]
- released 3/25/2016