简体   繁体   English

在javascript中引用父对象

[英]reference parent object in javascript

I'm new to javascript and struggling with a problem below. 我是javascript新手,并在下面遇到了问题。

Let's think about this situation. 让我们考虑一下这种情况。

First, there is an object like this. 首先,有一个像这样的物体。

var bar = {
            'name' : 'bob',
            'comments' : []
          }

However because of some reasons, we have only one variable that named 'foo' and this is exactly same with bar.comments . 但是由于某些原因,我们只有一个名为'foo'的变量,与bar.comments完全相同。

Second, because we need to reference the object bar , there must exist method in foo , named callParent . 其次,由于需要引用对象bar ,因此foo必须存在名为callParent If we satisfy all these condition, we can get object bar using foo.callParent() . 如果满足所有这些条件,则可以使用foo.callParent()获得对象bar

To implement like above, first of all, I define a constructor name Custom . 为了实现上述效果,首先,我定义一个构造函数名称Custom

function Custom(param){
    this.callParent = function(){
        console.log(param);
    }
}

and then, to use instance of Custom like array, inherit Array. 然后,要使用Custom实例(例如array),请继承Array。

Custom.prototype = Array.prototype;

after that, I want to define object bar as like below. 之后,我想定义对象bar ,如下所示。

var bar = {
            'name':'bob',
            'comments':new Custom(this)
          }

In that implementation, because I thought this means bar itself, I expected the result foo.callParent() will be bar but it was window . 在该实现中,因为我认为this意味着bar本身,所以我期望foo.callParent()的结果将是bar但它是window I think it's because in the context of calling foo.callParent() , this no longer means bar . 我认为这是因为在调用foo.callParent()的上下文中, this不再意味着bar

Finally, I solve this problem like this. 最后,我这样解决了这个问题。

var bar = {
            'name':'bob',
            'comments':undefined,
            'init':function(){
                        this.comments = new Custom(this);
                        return this;
            }
}.init();

Qeustion : Is there any way to solve this situation without help of other method like bar.init ? 问题 :如果没有诸如bar.init之类的其他方法的帮助,有什么方法可以解决这种情况? I want to solve this only with changes of constructor Custom ! 我只想通过更改构造函数Custom来解决这个问题! Is it related with IIFE ? 它与IIFE有关吗?

Try this: 尝试这个:

var bar = {
        'name':'bob'
      };
bar.comments = new Custom(bar);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM