Dinesh Kumar
Dinesh Kumar

Reputation: 21

Difference between object augmentation and class augmentation in javascript

When i have come across object and class augmentation, i read some online tutorial and understood that in object augmentation, we don't need to have prototype keyword to create variable and method to an object whereas in the class augmentation, we need to use prototype keyword to create variable and method to a function. Almost both does the same but i see approach is the only difference to create variable and method to an object. I want to understand the specific reason for object augmentation and class augmentation.

Upvotes: 2

Views: 1591

Answers (1)

Matt Greer
Matt Greer

Reputation: 62027

There are no true classes in JavaScript. It is an OO based language, but it uses prototypical inheritance to achieve that.

The general gist is:

  • When you augment the prototype, all objects with that prototype benefit and gain the functionality. The advantage is less memory is used as everyone shares the same function objects. It's also easier to simulate a class based language when using the prototype. The disadvantage is it's harder (but not impossible) to have anything that is truly private to to the object.

  • When you augment individual objects, you have more flexibility on how you build the objects. You can often achieve private state by using closures. The disadvantage is each object gets their own copy of the function objects, increasing memory usage. Another disadvantage is the objects are more "ad hoc" and it's more difficult to create "class" hierarchies with them. Many people argue creating those hierarchies is often not necessary or useful anyway.

The memory concerns are worth thinking about. When you're creating thousands of objects, that would mean many thousands of function objects in the object approach, and far far fewer function objects with the prototype approach.

Upvotes: 3

Related Questions