0

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?

2
  • 4
    Side note: Widget.prototype's constructor property already refers to Widget. You don't need Widget.prototype.constructor = Widget; unless you replace the object that Widget.prototype refers to. Commented Aug 4, 2016 at 16:58
  • Thank you for that clarification. This stuff is much different than other languages, but very cool. Commented Aug 4, 2016 at 17:29

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Gotcha, that makes sense. The issue I was having was accessing the functions from the constructor. I wasn't sure if I had to put the ".prototype" in there or not.
2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.