Jul 8, 2007

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.
  1. a function has property "prototype", the prototype object's points back to the function itself.
                function Dog(name)
                {
                }
                //the following are true
                alert(Dog.prototype.constructor == Dog);
                alert(Dog.constructor == Function);
                alert(Object.constructor == Function);
                
  2.             var spot = new Dog("fred");
                
    What does this mean? It means the above picture.
                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]
                
    The following change depict the property sovling process.

Now let's look how prototype inheritance work

            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();