【发布时间】:2017-03-05 17:38:04
【问题描述】:
对于任何未知数量的对象,如果需要,我想截取和更改某些属性。我尝试过 getter 和 setter,但我只能实现接近我想要的并且仅适用于已知对象。
以下是我想要达到的目标的示例:
在我的范围/闭包之外创建的对象
如您所见,这些是无法从外部访问的对象,我想做的是检查每个year_of_birth 属性,并在为任何未知对象创建或更改它时对其进行修改。我得到的最接近的是通过 getter/setter,但我必须传递对象,并且每次更改其值时它都会自行循环。
通过检查当前年份的年龄来尝试更正 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 正如我所解释的,我打算对我无法直接访问的任意数量的对象执行此操作。我提供的示例显示了这些对象是如何在一个自封闭匿名函数中生成的,我无法操作它的内容或将它们暴露给外部范围。
-
你想要的都是不可能的。
-
这是不可能的。如果某个库创建了私有对象,则应该非常不希望该对象因为您所做的某事而获得不同的行为或数据。
-
“在我的范围/闭包之外创建的对象”您如何完全意识到正在创建对象或访问这些对象?
标签: javascript object