javascript
javascript inheritance
Javascript has not class, it has only function. So its inheritance is somewhat confusing. Before we talk about inheritance, let's make sure we understanding the basic. Here is the fact.
<ol>
<li>a function has property "prototype", the prototype object's points back to the function itself.
<img src="http://msdn.microsoft.com/msdnmag/issues/07/05/JavaScript/fig03.gif" />
<pre data-sub="prettyprint:_">
function Dog(name)
{
}
//the following are true
alert(Dog.prototype.constructor == Dog);
alert(Dog.constructor == Function);
alert(Object.constructor == Function);
</pre>
</li>
<li>
<img src="http://msdn.microsoft.com/msdnmag/issues/07/05/JavaScript/fig05.gif" />
<pre data-sub="prettyprint:_">
var spot = new Dog("fred");
</pre>
What does this mean? It means the above picture.
<pre data-sub="prettyprint:_">
var spot = new Dog("Spot");
// Dog.prototype is the prototype of spot
alert(Dog.prototype.isPrototypeOf(spot));
// spot inherits the constructor property
// from Dog.prototype
alert(spot.constructor == Dog.prototype.constructor);
alert(spot.constructor == Dog);
// But constructor property doesn’t belong
// to spot. The line below displays "false"
//because a spot is not a function, only fucntion has constructor
alert(spot.hasOwnProperty("constructor"));
//but why spot.constructor is not null, it turns up that if the runtime find
//a property is null, it will check its prototype's property
// The constructor property belongs to Dog.prototype
// The line below displays “true”
alert(Dog.prototype.hasOwnProperty("constructor"));
alert(Dog.prototype) //alert [object Object]
</pre>
The following change depict the property sovling process.
<img src="http://msdn.microsoft.com/msdnmag/issues/07/05/JavaScript/fig06_L.gif" />
</li>
</ol>
<p>Now let's look how prototype inheritance work</p>
<pre data-sub="prettyprint:_">
function Pet()
{
this.walk = function()
{ alert("pet walk"); }
}
var p = new Pet();
p.walk();
function Dog(){}
//prototype is an instance(object)
Dog.prototype = p;
var d = new Dog();
d.walk();
</pre>