JavaScript 反射(reflect)所有对象引用中的属性更改

标签 javascript reference

我需要循环遍历嵌套对象类并在对象中提取它们的属性。但是从对象内部更改属性值不会更改保存这些对象的根对象的变量中的值。当我从对象内部检查时,新值已正确应用。

但是,如果我添加新属性而不是更改现有属性,我就可以访问新属性。

js fiddle

    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/

相关文章:

javascript - 我需要为计算机科学制作石头剪刀布,但我需要添加蜥蜴和史波克

javascript - Tapestry 5 - 在客户端字段验证成功/失败时运行 javascript 函数

java - 是否有必要为不可变对象(immutable对象)制作深拷贝

c++ - 将对非指针成员变量的引用作为指针返回可以吗?

javascript - 尝试通过 JS 和 Jquery 将文本引入 html 模板时,浏览器中出现 "undefined"

javascript - AngularJS 在 JSON 文件上嵌套 ng-repeat 和 ng-if

javascript - promise 中的地理定位

javascript - 变量名称和字符编码

Android Studio 库模块引用

vba - Microsoft Access - 缺少对 acrobat.tlb 的引用