Method inheritance in the JavaScript prototype chain -


"in javascript, every object has secret link object created it,forming chain. when object asked property not have,its parent object asked... continually chain until property found or until root object reached."

all , think above words truth now, did test verify , intended define relationship of objects below. please review .

enter image description here

the code should 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 move method can't found in square.prototype, javascript find in parent objects following chain, had thought found in rectangle.prototype, found in root shape.prototype , can't understand why sq.move(1,1) call shape.prototype.move instead of calling move method of rectangle.prototype ? did missed ?thanks.

you overwritten rectangle.prototype had move. since have overwritten it, move attached no longer there, that's why shape's move used.

rectangle.prototype.move = function(x, y) {   this.x += x;   this.y += y;   alert('rectangle move'); };  function square(){   shape.call(this); }  //overwritten prototype rectangle.prototype = object.create(shape.prototype); 

create prototype object first, before adding it.

rectangle.prototype = object.create(shape.prototype); rectangle.prototype.move = function (x, y) {   this.x += x;   this.y += y;   alert('rectangle move'); }; 

Comments