Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เข้าถึงตัวแปรใน Constructor Function ด้วย Prototype Method

ใช้ prototype เพิ่มเมธอดเข้าถึง Property ผ่าน this

ตัวอย่างโค้ด

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

Customer.prototype.setFullName = function(newFullName) {
    this.fullName = newFullName;
}

var customer = new Customer("John Smith");
console.log("Using Simple Method = " + customer.fullName);

customer.setFullName("David Miller");
console.log("Using Prototype Method = " + customer.fullName);

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo79.js)

ผลลัพธ์

Using Simple Method = John Smith
Using Prototype Method = David Miller