JSFiddle - React, Tailwind, and code Playground
by happyrupesh
Babel + JSX
function log(message) {
function actualLogDecorator(target, property, descriptor) {
console.log("\ngetFullName descriptor's value property")
console.log(descriptor.value)
var actualFunction = descriptor.value;
var decoratorFunc = function() {
console.log(message)
// Call the getFullName function on the humanObj object
return actualFunction.call(this)
}
// Here, we are overwriting the getFullName with the decoratorFunc which have log
// functionality and also actualFunction i.e. getFullName function
descriptor.value = decoratorFunc
console.log("\nNew descriptor's value proeprty due to decorator")
console.log(descriptor.value)
// This descript will overwrite the getFullName descriptor's value property
return descriptor
}
return actualLogDecorator
}
class Human {
constructor(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
@log("Logging by decorator")
getFullName() {
return this.firstName + " " + this.lastName
}
}
humanObj = new Human("Virat", "Kohli")
console.log("\ngetFullName's descriptor's value property after modification due to decorator")
// Human.prototype is used becuase class methods are defined on the prototpe property
descriptorObject = Object.getOwnPropertyDescriptor(Human.prototype, 'getFullName')
console.log(descriptorObject.value)
console.log("\nOutput for getFullName method")
console.log(humanObj.getFullName())