1

In Javascript, there are two ways you can define an object's properties:

First way

var myObject = {
  property1: function () {..},
  property2: function () {..}
};

Second Way

var myObject = {};
myObject.prototype.property1 = function() {...};
myObject.prototype.property2 = function() {...};

When I looked up prototype online, I found that it is used to add properties to an existing object. So, if you have an object which was created by a third party library, then you can add extra properties to it. What I don't understand is why you would use prototype for custom objects created in your own code. However, I have found many times (especially in Drupal core) that prototype is used this way. Why is this?

user1015214
  • 2,733
  • 10
  • 36
  • 66
  • Please first search before asking something that was asked several times before, even on StackOverflow. – trincot Feb 06 '18 at 20:41
  • Are you familiar with *prototypal inheritance*? – PM 77-1 Feb 06 '18 at 20:43
  • 1
    See also https://stackoverflow.com/questions/572897/how-does-javascript-prototype-work – IMSoP Feb 06 '18 at 20:43
  • @trincot I had looked around and must not have looked deep enough. https://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript is a great resource, thanks! – user1015214 Feb 06 '18 at 21:03

0 Answers0