Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Truy cập biến trong constructor function qua prototype method trong JavaScript

Sử dụng prototype để thêm phương thức cho constructor function, truy cập thuộc tính instance qua this.

Ví dụ

function Customer(fullName) {
    this.fullName = fullName;
}

// Thêm method vào prototype
Customer.prototype.setFullName = function(newFullName) {
    this.fullName = newFullName;
};

var customer = new Customer("John Smith");
console.log("Gọi trực tiếp: " + customer.fullName);

customer.setFullName("David Miller");
console.log("Gọi qua prototype: " + customer.fullName);

Cách chạy

node demo.js

Kết quả

Gọi trực tiếp: John Smith
Gọi qua prototype: David Miller

Lợi ích prototype: Method được chia sẻ giữa tất cả instance, tiết kiệm bộ nhớ so với định nghĩa method trong constructor.