Christian Christian - 1 year ago 59
Javascript Question

What's the difference between this.bla to Object.prototype.bla

Let's say I have this code:

(function(global) {
function Bar(foo) { = foo;
return this;

Bar.prototype.getFoo = function() {

Bar.prototype.setFoo = function(val) {
return ( = val);

What is the difference between creating functions like
and just doing it like this:

function Bar(foo) {
this.getFoo = function() {

I know what prototype is and what it means, I just can't figure out, why some people assign functions with prototype, because if I assign them with this, they will be available also every time I create a new instance of Bar.

Answer Source

The quick answer = function sharing + smaller memory footprint

When you're using prototype.functionName all instances share the same function (only one copy in memory), but if you use this.functionName in your constructor each instance has its own copy of the same function (exists multiple times in memory).

Using prototype has two implications:

  1. Memory footprint - as mentioned
  2. Subsequent function change on the prototype is reflected on all existing (and future of course) instances - there are rare occasions when one would like to do this, but it's there any it can be used

Advanced - you can have both

You can also have both in which case the local copy has precedence over the prototype which means that you could do stuff like this:

function Crazy(name)
{ = name;
    this.callMe = function() {
        return "Where are you " +;

Crazy.prototype.callMe = function() {
    return + " come here";

var inst = new Crazy("Robert");
inst.callMe(); // "Where are you Robert"
delete inst.callMe;
inst.callMe(); // "Robert come here"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download