Ok so I have been trying to figure out a way to make plain old Javascript have some sort of extension inheritance like many other OOP languages. But I have run into a specific problem, when a class extends a parent class using prototype each child of that object share variables rather than have their own new instance of the parent. For example:
TestB.prototype = new TestA();
function TestB(){ }
function TestA(){
var num = 0;
this.count = function(){
num ++;
console.log(num);
}
}
var test = new TestB();
test.count();
var test2 = new TestB();
test2.count();
So what happens is when the code is run the console looks like this:
1
2
Where as what I would prefer is for the “num” variable being inherited from the parent class to be unique to each respective instance and thus the output should be:
1
1
I assume this happens because when prototype is called it only creates a single new instance of TestA rather than one for each time TestB’s constructor is called. The problem is that I have not been able to find another way to make it work?
thanks for any help (and note this is actually for a more specific use but I just wanted to create a super simple test case to illustrate the problem cleanly. I do not have the freedom to use an external library such as jQuery or prototype.js to solve the problem)
You are not supposed to define methods in the constructor but in the prototype. This saves memory
, performs better as well as allows the class to be extended cleanly.