Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Defining prototype methods [duplicate]

Tags:

javascript

Is there a difference between this syntax

function Foo() {}

Foo.prototype.method1 = function() {};
Foo.prototype.method2 = function() {};

and this one?

function Foo() {}

Foo.prototype = {
    method1: function() {},
    method2: function() {}
}

Should one be prefered to the other?

like image 643
TheCat Avatar asked Aug 17 '26 09:08

TheCat


1 Answers

There is a slight difference between those two options. I would recommend using the former to preserve the constructor property pointing to the actual constructor function used to create the object. In the following example you'll see the difference under the hood of both options:

  • Foo used the prototype.newMethod syntax.
  • Bar used the prototype = {...} syntax.

Difference between extending the prototype and assigning an object to it

In case you'd like to use the Bar syntax, you can always set the constructor property to the correct function.

I hope this helps, let me know if you have any doubts.

like image 73
wilsotobianco Avatar answered Aug 20 '26 00:08

wilsotobianco