Context
Giả sử ta có ba Pokémon, mỗi Pokémon đều có một phương thức giống nhau:
const pokemons = [
{
name: "Pikachu",
getName() {
return this.name
},
},
{
name: "Charmander",
getName() {
return this.name
},
},
{
name: "Bulbasaur",
getName() {
return this.name
},
},
]Có thể tạo ra một prototype1 chung để cả ba đối tượng này kế thừa:
const pokemonPrototype = {
getName() {
return this.name
},
}
const pokemons = [
{ name: "Pikachu", __proto__: pokemonPrototype },
{ name: "Charmander", __proto__: pokemonPrototype },
{ name: "Bulbasaur", __proto__: pokemonPrototype },
]
console.log(pokemons[0].getName()) // "Pikachu"Lúc này, phương thức getName của cả ba đối tượng sẽ đều trỏ về một phương thức duy nhất nằm ở pokemonPrototype, giúp tiết kiệm được bộ nhớ.
Tuy nhiên, việc liên kết prototype ở mỗi đối tượng là dư thừa và không cần thiết, ta có thể dùng constructor function để tự động liên kết prototype cho tất cả các đối tượng được tạo ra thông qua toán tử new:
// `Pokemon` plays as a class
function Pokemon(name) {
this.name = name
}
Pokemon.prototype.getName = function () {
return this.name
}
const pokemons = [new Pokemon("Pikachu"), new Pokemon("Charmander"), new Pokemon("Bulbasaur")]
console.log(pokemons[0].getName()) // "Pikachu"Đối tượng Pokemon.prototype cũng tương tự như đối tượng pokemonPrototype ở ví dụ trước.
Attention
Lưu ý: constructor function không thể là arrow function.
Xem thêm: Anomalies in JavaScript arrow functions - LogRocket Blog
Constructor Code
Thuộc tính constructor gọi từ đối tượng sẽ trả về code của constructor:
console.log(pikachu.constructor)Kết quả trả về:
ƒ Pokemon(name, type, pokedex) {
// Properties
this.name = name
this.type = type
this.pokedex = pokedex
// Methods
this.getName = function () {
return `${name}`
}
}ES6
Info
Sau khi có ES6 với sự bổ sung của JS Class, người ta thay thế việc sử dụng constructor function thành
class.
// Before ES6
function Car(wheel, seats) {
this.wheel = wheel
this.seats = seats
}
// After ES6
class Car {
constructor(wheel, seats) {
this.wheel = wheel
this.seats = seats
}
}Resources
Footnotes
-
xem thêm JS Prototype ↩