3

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?

TheCat
  • 640
  • 1
  • 9
  • 23

1 Answers1

2

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.

wilsotobianco
  • 1,360
  • 14
  • 19
  • I'm confused. Isn't the empty Foo function the constructor? – TheCat Dec 26 '17 at 18:56
  • Yeah, but if you check the Bar example there's no constructor because the prototype was overridden by the object literal assignment. I think it is cleaner to use the `Foo` approach so you don't mess with the prototype chain. – wilsotobianco Dec 27 '17 at 01:53