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?
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
The this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.
Reports a constructor function that returns a primitive value. When called with new , this value will be lost and an object will be returned instead. To avoid warnings, use the @return tag to specify the return of the function.
Javascript's this
is not lexical. This means that makeChildren
gets its own this
instead of getting the Mother
's this
you want.
Set a normal variable to this and use it instead.
var that = this;
function makeChildren(){
blabla = that;
}
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:
this.children = children;
instead of returning a new object.
You could try passing a reference to the mother object when you call makeChildren() from within the mother object, something like this maybe:
var Mother = function() {
var children = makeChildren(this);
}
The makeChildren() function can then accept as an argument the reference, which you can use:
function makeChildren(ref)
var c = new Child(ref);
No idea whether or not that will work, but it might be worth a try.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With