I have two classes in JavaScript, with one inheriting from the other. The structure is as follows:
var Parent = (function(){
var self;
var parent = function(){
self = this;
self.type = 'Parent';
};
parent.prototype.getType = function(){
return self.type;
};
return parent;
})();
var Child = (function(){
var self;
var child = function(){
self = this;
Parent.call(self);
self.type = 'Child';
};
child.prototype = Object.create(Parent.prototype);
child.prototype.constructor = child;
return child;
})();
However, when I create an instance of Child, it changes the value of self
in the Parent class:
var parentInstance = new Parent();
var childInstance = new Child();
console.log(parentInstance.getType());
console.log(childInstance.getType());
The output is:
Child // I expected Parent
Child
I have a couple of questions:
- Why does this happen? I assumed that
self
, defined in the Parent class, would be a private variable unique to each Parent instance. I prefer wrapping my class definitions in a closure for organization, but I encounter issues like needing the
self
variable to access class scope for private methods.For example:
var Parent = (function(){ //... function _getType(){ return self.type; // 'this.type' is undefined here } })();
Is there a way to address this problem while still using the closure structure?
EDIT: solution for calling "private" methods
In _getType
, using this
would reference the Parent class instead of the object being created (e.g.,
parentInstance</code), so the issue can be resolved like this:</p>
<pre><code>var Parent = (function(){
var parent = function(){
this.type = 'Parent';
};
parent.prototype.callPrivateGetType = function(){
return _getType(this);
};
function _getType(that){
return that.type;
}
}
Now, running
var parentInstance = new Parent();
var childInstance = new Child();
console.log(parentInstance.callPrivateGetType());
console.log(childInstance.callPrivateGetType());
Will produce:
Parent
Child