I'm defining a Parent object, and I want it to have a child member object that has its own functions and private variables. In order to encapsulate the functions and variables, I'm adding a self-executing anonymous function to the Parent prototype.
Here is code demonstrating the problem:
var Parent = function() {
this.memberVariable = 'hello world';
}
Parent.prototype.doSomething = function() {
return this.childObject.doSomething();
};
Parent.prototype.childObject = function() {
// instead of being Parent, `this` is the Window object. What is the best way to fix this?
var that = this;
return {
doSomething: function() {
// undefined, but should be 'hello world'
return that.memberVariable;
}
}
}();
var parent = new Parent();
console.log(parent.doSomething());
One workaround I have is passing in the Parent scope to the child functions, but that seems weird, and it seems like there must be a better solution:
var Parent = function() {
this.memberVariable = 'hello world';
}
Parent.prototype.doSomething = function() {
// we pass in `this`
return this.childObject.doSomething(this);
};
Parent.prototype.childObject = function() {
return {
doSomething: function(that) {
return that.memberVariable;
}
}
}();
var parent = new Parent();
console.log(parent.doSomething());
Is there a better way to accomplish this?