I’m trying to define a class that, in its constructor, instantiates other objects and passes them a reference to itself:
var Child = function(m) {
var mother = m;
return {
mother: mother
}
}
var Mother = function() {
var children = makeChildren();
return {
children: children
}
function makeChildren() {
var children = [];
for (var i = 0; i < 10; i++) {
var c = new Child(this); // <--- 'this' is an empty object here
children.push(c)
}
return children;
}
}
This doesn’t work, and the Child instances end up with an empty object in their mother property. What is the proper way to do this?
Javascript’s
thisis not lexical. This means thatmakeChildrengets its ownthisinstead of getting theMother‘sthisyou want.Set a normal variable to this and use it instead.
I don’t think doing this is just enough though. By returning an object from the constructor you ignore the
this. Set things into it:instead of returning a new object.