Reputation: 439
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?
Upvotes: 2
Views: 967
Reputation: 2184
You can also use Object.getPrototypeOf(obj) as explained in this answer. But I had to amend your code to do this. I think you wanted to instantiate the Stats object, not its parent. Was that your intention?
function Person(){
this.age = 30;
}
function Stats(){
this.age = 20
}
Stats.prototype = new Person();
// Note that this is not your code example
var fred = new Stats();
console.log(fred.age)
console.log(Object.getPrototypeOf(fred).age);
Upvotes: 0
Reputation: 14318
Javascript supports both Classical and Prototypal Inheritance. Most other languages support only classical inheritance.
var person1 = {"fname" : "Amit", "lname":"Agar"};
var SubPerson = function(){};
SubPerson.prototype = person1;
var person2 = new SubPerson();
Reference javascript the good parts
Upvotes: 0
Reputation: 11740
JavaScript is nice enough to let you achieve what you want. Your use case requires that all constructors be invoked when a new type is created. Consider the following:
function defineClass(ctor, baseType) {
function classFunction() {
if (baseType) {
baseType.apply(this);
};
ctor.apply(this);
}
if (baseType) {
ctor.prototype = Object.create(baseType.prototype);
ctor.prototype.constructor = ctor;
}
classFunction.prototype = Object.create(ctor.prototype);
return classFunction;
}
Now you can define your two types:
function fruit() { console.log("fruit ctor"); }
var apple = defineClass(function apple() { console.log("apple ctor"); }, fruit);
Create a new apple:
new apple;
Console:
= fruit ctor
= apple ctor
Upvotes: 0
Reputation: 2912
have a look at "Introduction to Object-Oriented JavaScript" in the MDN: https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript
Upvotes: 0
Reputation: 22728
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 person
is the prototype for stats
anything 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.
Upvotes: 1
Reputation: 11779
In fact because of javascript have not classic object model, then you cannot get parent object ...
PS In your example "parent class" is Person, so when you create new person, parent will be object
Upvotes: 0