Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  84] [ 7]  / answers: 1 / hits: 28339  / 13 Years ago, thu, august 18, 2011, 12:00:00

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();

More From » javascript

 Answers
8

Sure there is a difference. If you define this.AlertA, you are defining a method that is local for the instance of ObjA. If you add AlertA to the prototype of the ObjA constructor, it is defined for every instance of ObjA. 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 of ObjA.



So using this.AlertA in:



var A = new ObjA, 
B = new ObjA,
C = new ObjA;


for A, B and C the constructor has to add the method AlertA. AlertB on the other hand, is only added once. You can check that using:



function ObjA() {
alert('adding AlertA!');
this.AlertA = function() {
alert(A);
};

if (!ObjA.prototype.AlertB) {
alert('adding AlertB!');
ObjA.prototype.AlertB = function() {
alert(B);
};
}
}

var A = new ObjA, //=> alerts adding AlertA! and alerts adding AlertB!
B = new ObjA, //=> alerts adding AlertA!
C = new ObjA; //=> alerts adding AlertA!

[#90548] Wednesday, August 17, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
quinn

Total Points: 160
Total Questions: 86
Total Answers: 101

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
;