نموذج تاريخ جافا سكريبت
مثال
أنشئ طريقة تاريخ جديدة تمنح كائن التاريخ خاصية اسم شهر تسمى 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"};
}
اصنع كائن تاريخ ، ثم استدع طريقة 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 المضمنة مثل:
- أعداد
- سلاسل
- المصفوفات
- بلح
- قيمة منطقية
- دور
- أشياء
فقط قم بتغيير النموذج الأولي للكائنات الخاصة بك.
خاصية النموذج الأولي
prototype
تتيح لك خاصية JavaScript إضافة خصائص جديدة إلى الكائنات:
مثال
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";