Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic Javascript Coding Style - when to declare functions on the prototype vs inside the function constructor [duplicate]

Tags:

javascript

In Javascript, when I want to declare a 'publicly' accessible function what is the idiomatic approach?

MyObj.prototype.foo = function() {
    ...
}

or

function MyObj() {
  this.foo = function() {
     ... 
  }
}

What situations would determine one style over the other? What are the advantages of one over the other?

Thanks a bunch for the help!

like image 635
Wade Anderson Avatar asked Aug 01 '26 14:08

Wade Anderson


1 Answers

The core difference

When a method declared on the prototype it's shared among all instances created by invoking the function as a constructor.

//assuming the first kind
var a = new MyObj();
var b = new MyObj();
//a and b both have the _same_ foo method

On the other hand, when it's created inside the class, each gets its own instance of the function.

//assuming the second kind
var a = new MyObj();
var b = new MyObj();
//a and b both have the _different_ foo methods

When it matters

Creating things on the prototype is useful for sharing functionality. It's faster than giving each instance its own copy of the method. However, if the construction creates closure the function will have access to it.

You can only access the closure of the creation in the second version

function MyObj(x) {
    var y = x;
    this.foo = function() {
         console.log(y);
    }
}

This is not possible in the first version. While this seems silly in this example sometimes closures are very useful. However, since the function now has access to the closure, even if it doesn't use it - it'll be slower. This is insignificant in 99% of cases but in performance intensive situations it might matter.

like image 167
Benjamin Gruenbaum Avatar answered Aug 03 '26 03:08

Benjamin Gruenbaum