Last active
January 10, 2017 10:42
-
-
Save ziaenezhad/5d8532e2b193464685286b079df5d88e to your computer and use it in GitHub Desktop.
Typescript General Parameter Injection Decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Inject(...args) { | |
return (target, propertyKey?: string, descriptor?: PropertyDescriptor) => { | |
if(propertyKey){ | |
var original_method:Function = descriptor.value; | |
descriptor.value = function(...params){ | |
original_method.apply(target, params.concat(args)); | |
}; | |
}else{ | |
// save a reference to the original constructor | |
var original_method = target; | |
// the new constructor behaviour | |
var f : any = function (...params) { | |
return original_method.apply(this, params.concat(args)); | |
} | |
// copy prototype so intanceof operator still works | |
f.prototype = original_method.prototype; | |
// return new constructor (will override original) | |
return f; | |
} | |
}; | |
} | |
//------------------------------- | |
//test | |
//------------------------------- | |
@Inject('name1') | |
class A{ | |
constructor(name, injected_name?) { | |
console.log(name, injected_name); | |
} | |
@Inject('name2') | |
print(name, injected_name?){ | |
console.log(name, injected_name); | |
this.print2(); | |
} | |
print2(){ | |
console.log('hehe'); | |
} | |
} | |
var ss = new A('ali'); | |
ss.print('reza'); | |
//------------------------------- | |
//output | |
//------------------------------- | |
ali name1 | |
reza name2 | |
hehe |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment