zadubz
zadubz

Reputation: 1301

What's the difference between these two ways of writting a prototype function in JavaScript

Myfunction.prototype.updateMyFunction = function() {

 //do something

};

Myfunction.prototype = {

 updateMyfunction: function() {

  //do something

 }

};

They both produce identical results

Upvotes: 1

Views: 63

Answers (2)

MD Sayem Ahmed
MD Sayem Ahmed

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

Tibos
Tibos

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

Related Questions