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?
var bar = { 'name':'bob', 'comments':new Custom(bar) }undefined.