3

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!

Wade Anderson
  • 2,461
  • 1
  • 20
  • 22
  • 1
    and [Declaring javascript object method in constructor function vs. in prototype](http://stackoverflow.com/q/9772307/218196) – Felix Kling Jul 09 '13 at 20:43
  • 1
    and [Javascript: when to define functions inside constructor and when to use prototype?](http://stackoverflow.com/q/13359363/218196) – Felix Kling Jul 09 '13 at 20:44

1 Answers1

2

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.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • You have a typo somewhere. I think the bold statement should be "in the second version"... ? – pedz Apr 26 '14 at 14:22