I play javascript with the book Professional JavaScript for Web Developers. I practice an example in section 6.2.6. the codes are listed below:
function creatPrototype(subType, superType)
{
function subTypePrototype(){};
subTypePrototype.prototype = superType.prototype;
subTypePrototype.constructor = subType;
subTypePrototype.str = "say";
return new subTypePrototype();
}
function Person(name, age)
{
this.name = name;
this.age = age;
}
Person.prototype.say = function(){
writeln("bill say");
}
function itMan(name, age){
Person.apply(this, arguments);
}
itMan.prototype = creatPrototype(itMan, Person);
var Bill = new itMan("bill", 25);
writeln(itMan.prototype.str); //expect "say"
writeln(Person.prototype == itMan.prototype.prototype); //expect true
Bill.say(); //expect "bill say"
the result is:
undefined
False
bill say
Why?
-
itMan.prototype.str is suppose to "say"
-
Person.prototype AND itMan.prototype.prototype should point to a same object
-
Bill.say() run correctly, so the prototype chain is OK.
You have to think about which property belongs to the constructor function and which one belongs to the instance.
prototypeis a property of the function, butconstructorandstrshould be both properties of the instance.This should do it:
But, as you are also passong
subType, you can actually assign the prototype directly:and then just call it with
Remember that
prototypeis a property of a function, not of objects. ButitMan.prototypeis a an object. You cannot access an objects prototype unless you explicitly refer to it (but I would not do so).With ECMAScript 5, there is a way to get the prototype, using
Object.getPrototypeOf[MDN]. This only works in newer browsers though.Here is a working example of your code.