JSFiddle - React, Tailwind, and code Playground
JavaScript
// Constructor
function Button() {
var self = this;
var _initialized = false;
this.initialized = false;
this.createButton();
this.initialized = true;
}
// Default prototype
Button.prototype = {
createButton: function() {
console.log(' create DOM element ');
}
}
// Default getter/setter on prototype
Object.defineProperty(Button.prototype,"initialized", {
set : function( bool ) {
console.log('this is the original setter');
this._initialized = bool;
if(this._initialized === true) {
console.log('do default stuff')
}
},
get : function() {
return this._initialized;
},
// IMPORTANT: this will allow us to redefine it
configurable : true
});
/************************************
THIS WOULD BE A SEPARATE FILE
Let's modify the class from here.
*************************************/
// Keep reference to the old accessors
var original = Object.getOwnPropertyDescriptor(Button.prototype, 'initialized');
Object.defineProperty(Button.prototype, "oldInitialized", {
set : original.set,
get : original.get
});
// Redefine getter and setter
Object.defineProperty(Button.prototype, "initialized", {
set : function( bool ) {
console.log('this is the new setter');
this.oldInitialized = bool;
},
get : function() {
return this._initialized;
}
});
// TEST: Create instance
var btn = new Button();
console.log(btn.initialized);
btn.initialized = false;