對於任何未知數量的對象,如果需要,我想截取和更改某些屬性。我已經嘗試過getter和setters,但是我只能靠近我想要的,只能用於已知對象。如何截取和修改任何對象的特定屬性
下面是什麼,我想實現的例子:我的範圍/關閉
之外創建
對象正如你可以看到這些是無法從外部訪問的對象,我想什麼要做的是檢查每個year_of_birth
屬性,並在創建或修改任何未知對象時對其進行修改。我得到的最接近的是getters/setters,但是我必須傳遞這個對象,並且每當它改變它的值時它就會自行循環。
試圖通過檢查年齡本年度糾正year_of_birth
一個例子
Object.defineProperty(unknown_object, 'year_of_birth', {
set: function(year) {
if (this.age && 2017 - this.age > year) {
this.year_of_birth = 2017 - this.age;
}
}
});
或
Object.defineProperty(unknown_object, 'year_of_birth', {
get: function(year) {
if (this.age && 2017 - this.age > year) {
return 2017 - this.age;
}
}
});
,但仍然沒有工作,只與我有奇異對象工作直接訪問。
有沒有辦法做到這一點?請不要使用像jQuery這樣的庫/框架解決方案。
編輯:代碼段的例子,因爲上面還不夠清楚:
// 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
你有你的對象的句柄?你是否控制了誰在你的代碼中引用了它? –
@MadaraUchiha正如我所解釋的,我打算爲任何數量的我無法直接訪問的對象執行此操作。我提供的例子展示瞭如何在一個自我封閉的匿名函數中產生這些對象,我無法操縱它的內容或將它們暴露給外部作用域。 – Shadow
你想要什麼是不可能的。 –