Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between object.key = fn() Vs object.prototype.key = fn()?

Option 1:

NotificationsService.push = function (notifications) {}

Option 2:

NotificationsService.prototype.push = function (notifications){}

Whats the difference between in defining a function directly vs on the prototype chain? Is it the inheritance?

like image 617
CuriousMind Avatar asked Dec 02 '25 04:12

CuriousMind


1 Answers

What is NotificationsService here?

If it is a function, then the difference is that in the second case, every instance of NotificationsService will inherit push.

var instance = new NotificationsService();
instance.push(...);

In the first case, you simply extend NotificationsService and it doesn't have any effect on instances created by it:

var instance = new NotificationsService();
instance.push(...); // will throw an error
NotificationsService.push(); // will work

If NotificationsService is an object, and we assume that NotificationsService.prototype exists and is an object, then it doesn't have anything to do with the prototype chain, you simply define the function at two different locations. This is a simpler example:

var foo = {};
var foo.prototype = {};

// defines a method on foo
foo.push = function() {...};

// defines a method on foo.prototype
foo.prototype.push = function() {...};

Those two properties don't have any relation to each other though.


To conclude: In both cases you are defining the method on different objects and as a consequence, have to be used differently. What to do depends on your use case.

like image 159
Felix Kling Avatar answered Dec 03 '25 19:12

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!