javascript获取父嵌套对象? [英] javascript get parent nested object?

查看:83
本文介绍了javascript获取父嵌套对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的对象:

I have an object like this for example:

obj = {
    subobj1: {

    },
    subobj2: {
        func1: function(){

        },
        func2: function(){

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

        },
        func4: function(){

        }        
    },
}

如何从中调用func1在func4内,无需调用obj.subobj2.func1()?

How do I call func1 from within func4 without having to call obj.subobj2.func1() ?

推荐答案

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

You can't exactly. You have no mean to know in what objects your function exists.

注意它可以是多个:你可以在现有代码之后写这个:

Note that it could be in more than one : you could have written this after your existing code :

var obj2 = {some:obj.subobj3};

因此,属性值不能有唯一的链接(并且没有可访问的链接)

So there can't be a unique link (and there is no accessible link) from a property value to the object holding it.

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

Now, supposing you'd be satisfied with a link made at object creation, you could use a factory to build your object :

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

        },
        subobj2: {
            func1: function(){

            },
            func2: function(){

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

            },
            func4: function(){
                parent.subobj2.func1();
            }        
        }
    };
    return parent;
})();

然后你可以致电

obj.subobj3.func4();

演示

编辑

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

I see you gave the tag OOP to your question. You should know that the pattern I gave is more frequently used to define modules. OOP in javascript is more often done using new and prototype, in order to enable instances sharing methods and inheritance. As you probably want modules rather than OOP, you seem to be fine, though.

参见本简介

这篇关于javascript获取父嵌套对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆