Inheriting a Method in the JavaScript Prototype Chain

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

That's all, I always think that the above words are true even now, so I did some tests to check this, I intended to determine the relationship of the objects, as shown below. please view it.

enter image description here

The code should look like this.

//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 cannot be found in Square.prototype , so JavaScript will find it in its parent objects following the chain, I thought it would be found in Rectangle.prototype , but actually it was found in the root of Shape.prototype . So I can’t understand why sq.move(1,1) actually calls Shape.prototype.move instead of calling the move Rectangle.prototype method? Am I missing something? Thanks.

+7
source share
2 answers

You just overwritten your Rectangle.prototype , which already had move . Since you overwrote it, the move you connected no longer exists, so a Shape 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); 

First create a prototype object 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'); }; 
+5
source

Move the prototype extension down. Now you assign a prototype after its extension, so it will overwrite the extended

 //Shape - superclass function Shape() { this.x = 0; this.y = 0; }; // Rectangle - subclass function Rectangle() { Shape.call(this); //call super constructor. } // Square - subclass function Square(){ Shape.call(this); } Rectangle.prototype = Object.create(Shape.prototype); Square.prototype = Object.create(Rectangle.prototype); Shape.prototype.move = function(x, y) { this.x += x; this.y += y; alert('Shape move'); }; Rectangle.prototype.move = function(x, y) { this.x += x; this.y += y; alert('Rectangle move'); }; var rect = new Rectangle(); var sq = new Square(); sq.x=1; sq.y=1; sq.move(1,1); 
+2
source

All Articles