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?
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:
prototype.newMethod syntax.prototype = {...} syntax.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With