Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototyped and a non-prototyped method? [duplicate]

I was wondering, what is the diferrence between a prototyped and a non-prototyped method in JavaScript? Any help is deeply appreciated.

like image 741
Alfa9Dev Avatar asked May 22 '12 15:05

Alfa9Dev


1 Answers

A non-prototyped method will take up memory in every instance of the class.

It will also (assuming it's declared in the scope of the class constructor) have access to any other private variables (or methods) declared in that scope.

For example, this will create an instance of the function per object, and that function can access myVar:

function MyObject() {
     var myVar;
     this.func = function() { ... };
};

and in this case there's only one instance of the function shared between every instance of the object, but it will not have access to myVar:

function MyObject() {
     var myVar;
};

MyObject.prototype.func = function() { ... };
like image 96
Alnitak Avatar answered Sep 28 '22 08:09

Alnitak