1

I'm new to javascript and struggling with a problem below.

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.

Second, because we need to reference the object bar, there must exist method in foo, named callParent. If we satisfy all these condition, we can get object bar using foo.callParent().

To implement like above, first of all, I define a constructor name Custom.

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

and then, to use instance of Custom like array, inherit Array.

Custom.prototype = Array.prototype;

after that, I want to define object bar as like below.

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. I think it's because in the context of calling foo.callParent(), this no longer means 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? I want to solve this only with changes of constructor Custom! Is it related with IIFE?

3
  • Like this ? var bar = { 'name':'bob', 'comments':new Custom(bar) } Commented Jan 12, 2016 at 16:27
  • 1
    @tresden that won't work - that will pass undefined. Commented Jan 12, 2016 at 16:28
  • @DanielA.White Oh, my bad. It should've been similar to your answer. Commented Jan 12, 2016 at 16:31

1 Answer 1

2

Try this:

var bar = {
        'name':'bob'
      };
bar.comments = new Custom(bar);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but I want to solve it with this which is used as parameter of Custom ! :D
@HT.Cha that overly complicates things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.