Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method inheritance in the JavaScript prototype chain

"In javascript, every object has a secret link to the object which created it,forming a chain. When an object is asked for a property that it does not have,its parent object is asked... continually up the chain until the property is found or until the root object is reached."

All , I always think the above words is truth even now, So I did some test to verify it , I intended to define the relationship of objects like below. please review it .

enter image description here

The code should look like below .

        //Shape - superclass
        function Shape() {
          this.x = 0;
          this.y = 0;
        };

        Shape.prototype.move = function(x, y) {
            this.x += x;
            this.y += y;

            alert('Shape move');
        };

        // Rectangle - subclass
        function Rectangle() {
          Shape.call(this); //call super constructor.
        }

        Rectangle.prototype.move = function(x, y) {
            this.x += x;
            this.y += y;

            alert('Rectangle move');
        };

        // Square - subclass
        function Square(){
            Shape.call(this);
        }

        Rectangle.prototype = Object.create(Shape.prototype);
        Square.prototype=Object.create(Rectangle.prototype);

        var rect = new Rectangle();

        var sq= new Square();

        sq.x=1;
        sq.y=1;
        sq.move(1,1);

Since the move method can't be found in the Square.prototype, So JavaScript will find it in its parent objects following the chain, I had thought It will be found in the Rectangle.prototype, but actually it is found in the root Shape.prototype , So What I can't understand is why sq.move(1,1) actually call the Shape.prototype.move instead of calling the move method of Rectangle.prototype ? Did I missed something ?thanks.

like image 512
Joe.wang Avatar asked May 15 '13 09:05

Joe.wang


1 Answers

You just overwritten your Rectangle.prototype which already had move. Since you have overwritten it, the move you attached is no longer there, that's why Shape's move is used.

Rectangle.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  alert('Rectangle move');
};

function Square(){
  Shape.call(this);
}

//overwritten the prototype
Rectangle.prototype = Object.create(Shape.prototype);

Create the prototype object first, before adding to it.

Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.move = function (x, y) {
  this.x += x;
  this.y += y;
  alert('Rectangle move');
};
like image 59
Joseph Avatar answered Oct 16 '22 05:10

Joseph