In Javascript is there any difference between these two ways of adding a function to an object? Is one preferable for any reason?
function ObjA() {
this.AlertA = function() { alert("A"); };
}
ObjA.prototype.AlertB = function() { alert("B"); };
var A = new ObjA();
A.AlertA();
A.AlertB();
Sure there is a difference. If you define
this.AlertA, you are defining a method that is local for the instance ofObjA. If you addAlertAto the prototype of theObjAconstructor, it is defined for every instance ofObjA. The latter is, in this case, more efficient, because it’s only assigned once, whilst a local method is assigned every time you create an instance ofObjA.So using
this.AlertAin:for A, B and C the constructor has to add the method
AlertA.AlertBon the other hand, is only added once. You can check that using: