Last active
January 22, 2016 09:50
-
-
Save frontdevops/de9444681e78740ca85d to your computer and use it in GitHub Desktop.
Set property decorator in TypeScript
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
/** | |
* Декоратор для логирования свойств | |
* @param target | |
* @param key | |
*/ | |
function logprop(target:any, key:string):void { | |
// получаем значение свойства | |
var val:any = this[key]; | |
// Делаем геттер с функцией логирования | |
const getter = function():any { | |
console.log(`Get: ${key} => ${val}`); | |
return val; | |
}; | |
// Делаем сеттер с функцией логирования | |
const setter = function (newVal):void { | |
console.log(`Set: ${key} => ${newVal}`); | |
val = newVal; | |
}; | |
// Пересоздаем свойство с геттером и сеттером | |
if (delete this[key]) | |
Object.defineProperty(target, key, { | |
get: getter, | |
set: setter, | |
enumerable: true, | |
configurable: true | |
}); | |
} | |
class Person { | |
@logprop public name:string; | |
@logprop public surname:string; | |
constructor(name:string, surname:string) { | |
this.name = name; | |
this.surname = surname; | |
} | |
} | |
let me = new Person("Alex", "Mayorov"); | |
me.name = "Alexander M."; | |
me.name; | |
/* Output: | |
Set: name => Alex | |
Set: surname => Mayorov | |
Set: name => Alex | |
Set: surname => Mayorov | |
Set: name => Alexander M. | |
Get: name => Alexander M. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment