A
A
aleks_web_dev2020-03-29 22:02:28
JavaScript
aleks_web_dev, 2020-03-29 22:02:28

Creating an object method in ES5 AND ES6 javascript?

I am delving into OOP in js and the question has arisen, or rather, did I understand one thing correctly

// создаю метод sayHay как свойство экземпляра класса
function UserCreate(name, age, rol) {
    this.name = name;
    this.age = age;
    this.rol = rol;

    this.sayHay = function() {
        console.log(`Hello: ${this.name},${this.age},${this.rol}`)
    }
}

let userOne = new UserCreate('Jon', 33, 'developer')
userOne.sayHay()


// создаю метод в прототипе класса 
function UserCreate(name, age, rol) {
    this.name = name;
    this.age = age;
    this.rol = rol;
}
UserCreate.prototype.sayHay = function() {
    console.log(`Hello: ${this.name},${this.age},${this.rol}`)
}

let userOne = new UserCreate('Jon', 33, 'developer')
userOne.sayHay()

// эта запись аналогична той которая выше ?
class UserCreate {
    constructor(name, age, rol) {
        this.name = name;
        this.age = age;
        this.rol = rol;
    }
    sayHay() {
        console.log(`Hello: ${this.name},${this.age},${this.rol}`)
    }
}

let userOne = new UserCreate('Jon', 33, 'developer')
userOne.sayHay()


The question is why we do not create a method as a property, as in the first example, but create a constructor in the prototype.
I understand this so that each instance of the class does not fill up the memory when we can define the method in the prototype and will be available to all instances Did I understand correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
L1nks, 2020-03-29
@aleks_web_dev

Let's say we have 100 User objects, each one will have a sayHello method and that fills up memory.
If we write to the prototype, then the method will be 1 and each of the User objects will refer to it along the prototype chain. So basically yes, you got it right.
And the record with the class is "syntactic sugar" - that is, the same functionality, just written a little easier.
Well written about classes on learn.javascript

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question