Answer the question
In order to leave comments, you need to log in
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()
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question