ต้นแบบวันที่ JavaScript
ตัวอย่าง
สร้างเมธอด date ใหม่ที่ทำให้อ็อบเจ็กต์ date มีคุณสมบัติเดือนชื่อ myName:
Date.prototype.myMonth = function()
{
if (this.getMonth()==0) {return "January"};
if (this.getMonth()==1) {return "February"};
if (this.getMonth()==2) {return "March"};
if (this.getMonth()==3) {return "April"};
if (this.getMonth()==4) {return "May"};
if (this.getMonth()==5) {return "June"};
if (this.getMonth()==6) {return "July"};
if (this.getMonth()==7) {return "August"};
if (this.getMonth()==8) {return "September"};
if (this.getMonth()==9) {return "October"};
if (this.getMonth()==10) {return "November"};
if (this.getMonth()==11) {return "December"};
}
สร้างวัตถุ Date จากนั้นเรียกใช้เมธอด myMonth:
const d = new Date();
let month = d.myMonth();
ความหมายและการใช้งาน
prototype
ให้คุณเพิ่มคุณสมบัติและวิธีการใหม่ให้กับวันที่
prototype
เป็นคุณสมบัติที่มีอยู่ในวัตถุ JavaScript ทั้งหมด
รองรับเบราว์เซอร์
prototype
เป็นคุณลักษณะ ECMAScript1 (ES1)
ES1 (JavaScript 1997) ได้รับการสนับสนุนอย่างสมบูรณ์ในเบราว์เซอร์ทั้งหมด:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |
ไวยากรณ์
Date.prototype.name = value
คำเตือน
คุณไม่แนะนำให้เปลี่ยนต้นแบบของวัตถุที่คุณไม่ได้ควบคุม
คุณไม่ควรเปลี่ยนต้นแบบของประเภทข้อมูล JavaScript ในตัวเช่น:
- ตัวเลข
- เครื่องสาย
- อาร์เรย์
- วันที่
- บูลีน
- การทำงาน
- วัตถุ
เปลี่ยนเฉพาะต้นแบบของวัตถุของคุณเอง
ทรัพย์สินต้นแบบ
คุณสมบัติ JavaScript prototype
ช่วยให้คุณเพิ่มคุณสมบัติใหม่ให้กับวัตถุ:
ตัวอย่าง
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";