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


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?


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


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();
snippet.log(a.theArray.length); // 1 -- so far, everything seems fine

var b = new MyConstructor();
snippet.log(b.theArray.length); // 2 -- huh?!?!
<!-- Script provides the `snippet` object, see -->
<script src=""></script>

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