This question is a continuation of another I asked here: How to intercept and modify a specific property for any Object
This is a method used to intercept any object's property of a certain name with the objective of changing the value or do a certain action when it is assigned or read:
Object.defineProperty(Object.prototype, "my_property", {
set: function (value) {
this._value = value;
},
get: function () {
return "changed";
}
});
var some_object = {};
some_object.my_property = "unchanged";
document.body.innerHTML += some_object.my_property;
My property value is:
While that method is working fine for values assigned to or read from properties after the object has been created, example:
var some_object = {}; // or new Object()
some_object.some_property = "some_value"; // triggers setter
console.log(some_object.some_property); // triggers getter
It won't trigger the getter and setter if the property has been initialized together with the object using literal notation, like so:
var some_object = {some_property: "some_value"}; // does not trigger setter
console.log(some_object.some_property); // does not trigger getter
How can I adapt the previous strategy so that it can also work with the literal notation or is there a different way of achieving this using a completely different method? Perhaps by intercepting the creation of any object through literal notation, similar to monkey patching the Object.create() function?
Keep in mind that this is only to target a property of a known name on any unknown object.