JavaScript Decorators

by nabendu

Babel + JSX

let wheels = function(target) {
  target.noOfWheels = 4;
}
let doors = function(number) {
	return function(target) {
  	target.noOfDoors = number;
  }
}
let readOnly = function(target, key, descriptor) {
	descriptor.writable = false;
  return descriptor;
}

@wheels
@doors(2)
class Car {
	constructor(color) {
  	this.color = color;
  }  
  @readOnly
  getColor() {
  	return this.color;
  }
}

const redCar = new Car('red');

redCar.getColor = function() {
	return 'I will over-ride';
}

console.log(redCar.getColor());  //red
console.log(`Wheels - ${Car.noOfWheels}`); //Wheels - 4
console.log(`Doors - ${Car.noOfDoors}`); //Doors - 2