I have the following code:
function Person(){
this.age = 30;
}
function Stats(){
this.age = 20
}
Stats.prototype = new Person();
var fred = new Person();
console.log(fred.age)
What I am trying to do is understand inheritance in Javascript, how can I do the above and get the age property in both stats and person?
You can’t. JavaScript doesn’t do classical inheritance, but rather Prototypal inheritance. Have a look at crockford’s article on this (as well as many others.)
Since
personis the prototype forstatsanything that is part of the person prototype will be overridden by setting that attribute in the instantiated object.But the cool part is that if you change the prototype, all objects which have that object as its prototype will receive the change.
There are some projects out there which try to shim classical inheritance into JavaScript, but rather than working against it, you should learn to embrace it.