Question about declaring an object in Javascript

What is the difference between this:

function Book() { this.title = ''; this.setTitle = function(title) { this.title = title; } } 

or that:

 function Book() { } Book.prototype.title = ''; Book.prototype.setTitle = function(title) { this.title = title; } 

Is there any difference other than syntax?

+4
source share
4 answers

You should probably read about prototypes .

In the first example, you set the setTitle function on the very same instance of Book that is being created.

In the second example, you use prototype inheritance, in other words, all Books now inherit the same setTitle function.

The second saves memory, and functions are easier to update in all Book instances.

But the first has its own precedents, since you can leave the this header on the header and make the variable private with closures .

 function Book(title) { var title = title; this.getTitle = function() { // function keeps a reference to title return title; // now we only have a getter, but no setter for title // thus title is essentially private } } 
+3
source

When using Book.prototype.setTitle, only one setTitle function is created and reused for all future book instances.

In the first example, each book instance will create each setTitle function of its own.

Therefore, it is recommended to use a prototype.

+2
source

the first sets the title property and the setTitle method directly to the book instance. the second puts these members in the prototype of the book. The second, usually the best approach for JavaScript OOP.

0
source

This great SO question from yesterday will explain the differences between your two examples: Why JavaScript prototyping?

0
source

Source: https://habr.com/ru/post/1335228/


All Articles