Suppose I have two constructor function:
var Person = function(xx,xx,xxx,xxxxxxx) {
//Person initialization
}
var Man = function(xx,xx,xxx,xxx) {
//Man initialization
}
And I want Man extends from Person.
The following is what I thought:
Given a created Man object:
var m=new Man("xx",....);
1) when a property of m is accessed,it will search it in Man.prototype.
2) If not find, It should find it in Man.prototype.__prop__.
So what I have do is make the Man.prototype.__prop__ linked to Person.prototype.
I know this is the common way:
function inherit(superClass) {
function F() {}
F.prototype = superClass.prototype;
return new F;
}
Man.prototype=inherit(Person);
But when I try this:
Man.prototype.prototype=Person.prototype.
Why it does not work?
It sounds like you actually want to link instances of
Manto an instance ofPersonthat retains any properties added in its constructor, in which case you might really want something like this:…which prints
val1.Additional Ramblings
The purpose of
inheritis to create an object from a function whoseprototypeis that of the given super class (without explicitly usingnew), which is exactly what it does. Therefore, the following printsstring:But you generally want to assign the returned object to another function’s prototype:
…so that
m.testalso printsstring, which means that objects created usingManare linked toPerson‘sprototype).Note that
Man.prototype.prototypeisundefinedand — this is the important part — also meaningless. Functions have prototypes. Other objects (such asMan.prototype) do not. Theprototypeproperty is not magical in any other context. Assigning a value to a random object’sprototypeproperty doesn’t do anything special. It’s just another property.Note also that the thing we returned from
inheritis linked toPersonby way of itsprototypeand has no access to any properties added to instances ofPerson.