javascript获取父嵌套对象?

Joe*_*Joe 6 javascript oop object

我有一个这样的对象,例如:

obj = {
    subobj1: {

    },
    subobj2: {
        func1: function(){

        },
        func2: function(){

        }
    },
    subobj3: {
        func3: function(){

        },
        func4: function(){

        }        
    },
}
Run Code Online (Sandbox Code Playgroud)

如何在func4中调用func1而不必调用obj.subobj2.func1()?

Den*_*ret 13

你不能完全.你无意知道你的函数存在于哪些对象中.

请注意,它可能不止一个:您可以在现有代码之后编写:

var obj2 = {some:obj.subobj3};
Run Code Online (Sandbox Code Playgroud)

因此,从属性值到持有它的对象不能有唯一的链接(并且没有可访问的链接).

现在,假设您对在对象创建时创建的链接感到满意,您可以使用工厂来构建对象:

obj = (function(){
    var parent = {
        subobj1: {

        },
        subobj2: {
            func1: function(){

            },
            func2: function(){

            }
        },
        subobj3: {
            func3: function(){

            },
            func4: function(){
                parent.subobj2.func1();
            }        
        }
    };
    return parent;
})();
Run Code Online (Sandbox Code Playgroud)

然后你可以打电话

obj.subobj3.func4();
Run Code Online (Sandbox Code Playgroud)

示范


编辑

我看到你给你的问题标记OOP了.您应该知道我给出的模式更常用于定义模块.javascript中的OOP通常使用new和完成prototype,以便启用实例共享方法和继承.因为你可能想要模块而不是OOP,但你看起来很好.

这个介绍.


Poi*_*ess 5

这是.parent通过递归init 添加到任何子对象的方法:

var obj = {
    init: function() {
        for (var i in this) {
            if (typeof this[i] == 'object') {
                    this[i].init = this.init;
                    this[i].init();
                    this[i].parent = this;
            }
        }
        return this;
    },
    subobj1: {
    },
    subobj2: {
        func1: function(){
            console.log('hey');
        },
        func2: function(){
        }
    },
    subobj3: {
        func3: function(){
        },
        func4: function(){
            this.parent.subobj2.func1();
        }        
    }
}.init();

obj.subobj3.func4();
Run Code Online (Sandbox Code Playgroud)

使用此解决方案,您还可以.parent根据嵌套需要使用多次,例如,如果您有两个嵌套级别:

this.parent.parent.subobjX.funcY();
Run Code Online (Sandbox Code Playgroud)

http://jsbin.com/yuwiducadoma/1/watch?js,控制台