A
A
Artem Gavrilyuk2019-08-01 16:18:24
JavaScript
Artem Gavrilyuk, 2019-08-01 16:18:24

How to describe methods in a JS object?

Tell me what is the difference in the description of methods in the object? It's just that in the first case, the method is described in each instance of the object, and in the second case, in the prototype of the object. Roughly speaking in the second variant we avoid code duplication???
Thank you all in advance for your replies!

function Car(name, year) {
    this.name = name;
    this.year = year;
    this.getYear = () => new Date().getFullYear() - this.year;
}

function Car(name, year) {
    this.name = name;
    this.year = year;
}

Car.prototype.getYear = () => new Date().getFullYear() - this.year;

5d42e68cda240835185206.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2019-08-01
@goodlycoder

Not duplication, but the cost of creating this object () => new Date().getFullYear() - this.year;
In addition, in the first case, you assign a function to the property of the object, and in the second, you create a method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question