Decorators demo
Code snippet for a tutorial
by iamshadmirza
Babel + JSX
/*
Let's say we have a room and we want to decorate it with a some cool stuff
These stuff can be written as a functions in javascript
Let's create a poster
*/
function poster(target){
target.poster = "Avengers";
}
//Let's add some wallpaper
function wallpaper(target){
target.wallpaper = "Vinyl"
}
//Let's decorate our room
//You just have to add the decorator at top of the class
@poster
@wallpaper
class MyRoom {}
console.log(`My room is decorated with ${MyRoom.poster} poster and has beautiful ${MyRoom.wallpaper} wallpaper`);
/*
My room is decorated with Avengers poster and has beautiful Vinyl wallpaper
*/
//Let's assume we want add owner name also. decorator for that can be created as
function owner(name){
return function(target){
target.owner = name;
}
}
//Then MyRoom can be defined as
@poster
@wallpaper
@owner("Shad")
class ShadsRoom {}
//Let's check if it's working
console.log(`${ShadsRoom.owner}'s room is decorated with ${ShadsRoom.poster} poster and has beautiful ${ShadsRoom.wallpaper} wallpaper`);