我需要循环遍历嵌套对象类并在对象中提取它们的属性。但是从对象内部更改属性值不会更改保存这些对象的根对象的变量中的值。当我从对象内部检查时,新值已正确应用。
但是,如果我添加新属性而不是更改现有属性,我就可以访问新属性。
var OO = function(o, parent){
this.parent = parent || null;
this.init(o);
return this;
};
OO.prototype = {
init: function(o){
this.obj = typeof o === 'object' ? new OO(o.name, this) : o;
this.type = typeof o === 'object' ? 'object' : 'string';
if( typeof o === 'string' ){
this.change();
console.log(this.parent); // Here top-level oo object holds values called in change() function. I want the variable ( oo_var ) holding this top-level oo to have same property values too.
this.add();
}
},
change: function(){
this.parent.obj = 'Orange'; // Holds {} before changing
this.parent.type = 'string'; // 'object' before changing
},
add: function(){
this.parent.another_obj = 'Another';
this.parent.another_type = 'another string';
}
};
var oo_var = new OO({name: 'Apple'}); // This var doesn't refresh the obj & type property values applied in change() function. But has properties added in add() function.
我有很多级别的嵌套对象,每个级别都有同级对象。
最佳答案
构造函数应该只进行创建,而不是改变任何东西的状态。它不需要调用 init
方法,并且绝对不应该调用(即使是间接)change
方法。
成功
function OO(o, parent) {
this.parent = parent || null;
this.type = typeof o;
this.obj = this.type === 'object' ? new OO(o.name, this) : o;
}
OO.prototype.change = function() {
this.parent.obj = 'Orange'; // Holds {} before changing
this.parent.type = 'string'; // 'object' before changing
};
OO.prototype.add = function(){
this.parent.another_obj = 'Another';
this.parent.another_type = 'another string';
};
var oo_var = new OO({name: 'Apple'});
console.dir(oo_var);
oo_var.obj.change();
oo_var.obj.add();
console.dir(oo_var);
让子级更改父级而不是父级更改本身也有点奇怪( if not wrong )。
如果您不想自己调用这些方法,您可以使用一个方法:
OO.prototype.init = function() {
if (this.type === 'object' ) {
this.obj.init();
} else if (this.type === 'string') {
this.change();
this.add();
}
};
var oo_var = new OO({name: 'Apple'});
console.dir(oo_var);
oo_var.init();
console.dir(oo_var);
关于JavaScript 反射(reflect)所有对象引用中的属性更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39913155/