user2094477
user2094477

Reputation:

Javascript prototypes, how to access prototype functions

New to this whole concept of prototypes in Javascript and might be confused.

Let's say I have a class called Widget, defined as:

var Widget = function (options) {
    // constructor code here
}

Widget.prototype.constructor = Widget;
Widget.prototype.myGreatFunction = function(){}

Should I be able to call Widget.myGreatFunction(); or do I need to call Widget.prototype.myGreatFunction()? to run the great function?

Upvotes: 0

Views: 1255

Answers (2)

Ayan
Ayan

Reputation: 2380

Ideal way of doing so is creating an instance and using the prototypal functions. Nevertheless as the function is stored in Widget.prototype.myGreatFunction you can definitely access it.

The functions defined in the prototype are shared resources and thats the prime advantage of using it in this manner.

var Widget = function (options) {
    // constructor code here
}

Widget.prototype.constructor = Widget;
Widget.prototype.myGreatFunction = function(i){console.log('myGreatFunction', i);};

var a = new Widget();
a.myGreatFunction(1);


var b = new Widget();
b.myGreatFunction(2);

Upvotes: 2

Pointy
Pointy

Reputation: 413720

If you use your constructor function to make an instance, you can use the function from there:

var w = new Widget();
w.myGreatFunction();

You can also use the function by referring to it via the prototype:

Widget.prototype.myGreatFunction();

Upvotes: 3

Related Questions