2
function Demo() {
   this.show1 = function() { alert(1) }
}

Demo.prototype.show2 = function() { alert(2) }

var d = new Demo
d.show1()
d.show2()

show1 and show2 can both alert number.

Is there any difference between these two?

Ranjit Singh
  • 3,715
  • 1
  • 21
  • 35
user1726273
  • 115
  • 4
  • Except re-usability, readability, etc? Read this for instance: http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work – walther Oct 07 '12 at 07:01

2 Answers2

6

Yes, if you initialize that method inside the constructor, e.g. (this.method = function () {};), all of your 1000 object instances will have a function object as own property.

Well, it's the most lightweight way to go, let's say you have a method in the prototype of certain constructor, and you create 1000 object instances, all those objects will have your method in their prototype chain, and all of them will refer to only one function object.

In the second case, only those objects, which get created after the Demo.prototype.show2 = function(){alert(2)} will get the code. :)

Example

Your code

function Demo(){
   this.show1 = function(){alert(1)}
}

Demo.prototype.show2 = function(){alert(2)}

var d = new Demo
d.show1()
d.show2()

Other Case

function Demo(){
   this.show1 = function(){alert(1)}
}

var d = new Demo

Demo.prototype.show2 = function(){alert(2)}

d.show1()
d.show2()
Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
2

show1 is replicated on every new instance. show2 is shared.

elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • do you mean that the second case is somehow similar to static methods but the first is non-static if compared with java? – user1406062 Oct 07 '12 at 07:05
  • @HussainAl-Mutawa: I think so yes, similar to static methods but you have access to `this` and it requires an instance of the object to be used. – elclanrs Oct 07 '12 at 07:08