Aymen Kareem Aymen Kareem - 1 month ago 7
Javascript Question

What is the difference between Adding Methods to Javascript Prototype and Adding Functionality to Existing Objects

I read in a book that we can extend functionality of existing objects using the following code:

var Point = function(x, y) {
this.x = x;
this.y = y;
}

Point.prototype.moveBy = function(deltaX, deltaY) {
this.x += deltaX;
this.y += deltaY;
}
Point.prototype.moveTo = function(otherPoint) {
this.x = otherPoint.x;
this.y = otherPoint.y;
}
var p1= new Point(100, 200);
p1.moveBy(10, 20);
var p2= new Point(25, 50);
p2.moveTo(p1);
alert("p2.x: " + p2.x + " p2.y: " + p2.y);


I just found that I can get the same results with prototype as follows:

var Point = function(x, y) {
this.x = x;
this.y = y;
}

Point.prototype = {
moveBy: function(deltaX, deltaY) {
this.x += deltaX;
this.y += deltaY;
},

moveTo: function(otherPoint) {
this.x = otherPoint.x;
this.y = otherPoint.y;
}
};
var p1= new Point(100, 200);
p1.moveBy(10, 20);
var p2= new Point(25, 50);
p2.moveTo(p1);
alert("p2.x: " + p2.x + " p2.y: " + p2.y);


var p1= new Point(100, 200);
p1.moveBy(10, 20);
var p2= new Point(25, 50);
p2.moveTo(p1);
alert("p2.x: " + p2.x + " p2.y: " + p2.y);


So what is the difference? It did not make sense to me.
What Object are we adding functionality to?
What is the difference if we created the functions as methods in the Point object?
Why don't we do it using Prototype only?

Answer

Well the difference is clear. With the first peace of code your are declaring new members for Point.prototype. However, in the second one, you are providing an entire implementantion for Point.prototype.

All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype, although they may be overridden (except an Object with a null prototype, i.e. Object.create(null)). For example, other constructors' prototypes override the constructor property and provide their own toString() methods.

Changes to the Object prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior. Object.prototype on MDN

Comments