Reputation: 1301
Myfunction.prototype.updateMyFunction = function() {
//do something
};
Myfunction.prototype = {
updateMyfunction: function() {
//do something
}
};
They both produce identical results
Upvotes: 1
Views: 63
Reputation: 29166
The first one is adding a property to Myfunction.prototype
, while the second one completely replacing the Myfunction.prototype
with a new object.
The result will not be always identical. Consider this case -
Myfunction.prototype.oldMethod = function () {
};
Myfunction.prototype.updateMyFunction = function() {
//do something
};
After adding the last method, you will be able to access both oldMethod
and updateMyFunction
later. If you do this -
Myfunction.prototype.oldMethod = function () {
};
Myfunction.prototype = {
updateMyfunction: function() {
//do something
}
};
then the oldMethod
will be removed from the prototype chain (since the prototype
itself is being replaced with a new object) and you will not be able to access it anymore.
Upvotes: 6
Reputation: 27823
The first one uses the already-existing prototype of MyFunction, while the second one replaces the prototype with a new object.
Some surprising problem with replacing the prototype:
var MyFunction = function(){
};
var obj = new MyFunction();
MyFunction.prototype = {
updateMyfunction: function() {}
};
var obj2 = new MyFunction();
console.log(obj2 instanceof MyFunction) // true as expected
console.log(obj instanceof MyFunction) // false because the prototype changed
Upvotes: 0