0

Option 1:

<script>
function Gadget(name, color) { 
   this.name = name; 
   this.color = color; 
   this.whatAreYou = function(){ 
     return 'I am a ' + this.color + ' ' + this.name; 
   }
}
var user = new Gadget('David', 'White');
console.log(user.whatAreYou());
</script>

Option 2:

<script>
function Gadget(name, color) { 
   this.name = name; 
   this.color = color;  

}
Gadget.prototype = {
    whatAreYou: function(){ 
     return 'I am a ' + this.color + ' ' + this.name; 
   }
}
var user = new Gadget('David', 'White');
console.log(user.whatAreYou());
</script>

Question:

Option 1, I put method into function(); Option 2, I added method through prototype, Both of them work. But is there any differnce in these two options when create objects?

user2294256
  • 1,029
  • 1
  • 13
  • 22
  • 2
    Ref. http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript , http://stackoverflow.com/questions/4270388/what-is-the-difference-between-assigning-a-function-via-this-vs-prototype?rq=1 , http://stackoverflow.com/questions/8244101/what-is-difference-between-method-attached-to-prototype-or-object-instance-in-ja?rq=1 (and many, many more) – user2246674 Jun 18 '13 at 03:30

2 Answers2

4

With Option 1, if you create 100 Gadgets, 100 whatAreYou functions are created for each object in memory.

With Option 2, if you create 100 Gadgets, only 1 whatAreYou function exists in memory, with each Gadget having a link to that function through the Gadget's prototype

Basically using prototype is more memory efficient.

CheapSteaks
  • 4,821
  • 3
  • 31
  • 48
1

The prototype is JavaScript's form of object oriented code. It associates the method with all instances of Gadget.

Option1 will just add the method to a single instance, so other instances of gadget will not see it. Instead there will exist a local copy of the method in all instances which means you will experience the creation overhead and memory footprint n times

TGH
  • 38,769
  • 12
  • 102
  • 135
  • you won't really have a footprint of n because the JS engine is allowed to recycle identical functions internally. Maybe IE7 is that lame, but nothing recent would be so naive... – dandavis Jun 18 '13 at 04:30
  • Probably true, but it's still at the mercy of the browser vendor... It's a bit like compiler optimization in C# etc :-) – TGH Jun 18 '13 at 04:33