13

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();
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • Possbible duplicate: http://stackoverflow.com/questions/422476/javascript-setting-methods-through-prototype-object-or-in-constructor-differenc – Digital Plane Aug 18 '11 at 15:39
  • possible duplicate of [Use of 'prototype' vs. 'this' in JavaScript?](http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript) – user2864740 Nov 11 '14 at 06:49

2 Answers2

16

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!
Ashish Aggarwal
  • 3,018
  • 2
  • 23
  • 46
KooiInc
  • 119,216
  • 31
  • 141
  • 177
3

Using the object constructor will assign a copy of that function to every new instance of your object. Using prototyping will result in one function being shared across all instances.

heisenberg
  • 9,665
  • 1
  • 30
  • 38