Is it better to declare variables inside or outside the prototype property?

advertisements

This question already has an answer here:

  • Use of 'prototype' vs. 'this' in JavaScript? 14 answers

Which of the following cases is better for performance or proper techniques?

CASE #1

function SomeClass ()
{
    this.someVar = null;
    this.someFunc = function () {}
}

CASE #2

function SomeClass () {}
SomeClass.prototype.someVar = null;
SomeClass.prototype.someFunc = function () {}


It depends entirely on whether you want them shared between instances created via that constructor function. If you do, put them on the prototype. If you don't, set them up in the constructor.

Beware that putting references to objects/arrays on the prototype is likely to trip you up, as (again) all instances will share those references.

Putting methods (references to functions) on the prototype is fairly standard practice.


Here's an example of getting tripped up by putting an array on the prototype:

function MyConstructor() {
};
MyConstructor.prototype.theArray = []; // Don't do this unless you're really sure

var a = new MyConstructor();
a.theArray.push("foo");
snippet.log(a.theArray.length); // 1 -- so far, everything seems fine

var b = new MyConstructor();
b.theArray.push("bar");
snippet.log(b.theArray.length); // 2 -- huh?!?!
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

The reason, of course, is that both a and b are using the same array: The one on the prototype.