For any unknown number of objects, there are certain properties I want to intercept and change if needed. I have tried getters and setters, but I was only able to achieve close to what I wanted and only for known objects.
The following are examples of what I am trying to achieve:
Objects being created outside of my scope/closure
As you can see these are objects that cannot be accessed from outside and what I want to do is check every year_of_birth
property and modify it whenever it is created or altered for any unknown object. The closest I got was through getters/setters, but I had to pass the object and it would loop itself every time it change its value.
An example that tries to correct the year_of_birth
by checking the age with the current year
Object.defineProperty(unknown_object, 'year_of_birth', {
set: function(year) {
if (this.age && 2017 - this.age > year) {
this.year_of_birth = 2017 - this.age;
}
}
});
or
Object.defineProperty(unknown_object, 'year_of_birth', {
get: function(year) {
if (this.age && 2017 - this.age > year) {
return 2017 - this.age;
}
}
});
but still did not work well and only worked with singular objects that I had direct access.
Is there any way to do this? Please no solutions with libraries/frameworks like jQuery.
EDIT: Snippet example because the above was not clear enough:
// Here I define some sort of solution to manipulate any object property of name "year_of_birth"
// unknown_object or a sort of prototype/constructor that intercepts any object, regardless of its scope
Object.defineProperty(unknown_object, 'year_of_birth', {
set: function(year) {
if (this.age && 2017 - this.age > year) {
this.year_of_birth = 2017 - this.age;
}
}
});
// or
Object.defineProperty(unknown_object, 'year_of_birth', {
get: function(year) {
if (this.age && 2017 - this.age > year) {
return 2017 - this.age;
}
}
});
// I want to modify "year_of_birth" or any other object property that is inside the below scope
// I do not have access to that scope, I cannot modify the function to allow access to its scope, I cannot do anything to it besides trying to modify the objects from the outside through some method that I am trying to find out in this question
(function() {
var john = {
age: 28,
year_of_birth: 1985
};
var anne = {
age: 31,
year_of_birth: 1985
};
}());
// Whenever a "year_of_birth" object property is read/set it should change to whichever value it has been established in the setters/getters at the top