Object Prototypes trong JavaScript
1. Việc kế thừa prototype
– Tất cả các object JavaScript kế thừa các properties và methods từ một prototype.
– Date objects kế thừa từ Date.prototype. Array objects kế thừa từ Array.prototype. Car objects thừa kế từ Car.prototype.
– Object.prototype nằm ở trên cùng (top) của chuỗi thừa kế prototype.
– Date objects, Array objects, và Car objects kế thừa từ Object.prototype.
2. Cách sử dụng property prototype
– Ở bài viết trước Object Constructors trong JavaScript chúng ta đã biết rằng: không thể thêm property mới hay method mới ở bên ngoài một object constructor.
// Constructor function
function Car(in_brand, in_name, in_weight, in_color) {
this.brand = in_brand;
this.name = in_name;
this.weight = in_weight;
this.color = in_color;
}
// Tạo đối tượng myCar từ constructor Car
var myCar = new Car("Toyota", "Prius 2018", 850, "White");
– Nhưng nếu sử dụng property prototype thì điều đó hoàn toàn có thể và được thực hiện rất dễ dàng:
Ví dụ: Sử dụng property prototype thêm property mới cho object constructor:
// CÓ THỂ thêm property mới vào một "constructor function" // bằng cách sử dụng property "prototype" Car.prototype.nation = "Japan"; myCar.nation; //return JapanTry it »
Ví dụ: Sử dụng property prototype thêm method mới cho object constructor:
// CÓ THỂ thêm method mới vào một "constructor function"
// bằng cách sử dụng property "prototype"
Car.prototype.getFullName = function() {
return this.brand + " " + this.name;
};
myCar.getFullName(); // return Toyota Prius 2018
Try it »Chỉ modify các prototypes (nguyên mẫu) do chính bạn định nghĩa ra. Không bao giờ được modify các prototypes của các đối tượng tiêu chuẩn của JavaScript (standard JavaScript objects).

[…] Có thể bạn quan tâm: Object Prototypes trong JavaScript. […]