JavaScript Datum prototipe
Voorbeeld
Maak 'n nuwe datummetode wat die datumobjek 'n maandnaam-eienskap genaamd myName gee:
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"};
}
Maak 'n Date-objek en roep dan die myMonth-metode:
const d = new Date();
let month = d.myMonth();
Definisie en gebruik
prototype
laat jou toe om nuwe eienskappe en metodes by datums te voeg.
prototype
is 'n eiendom wat beskikbaar is met alle JavaScript-objekte.
Blaaierondersteuning
prototype
is 'n ECMAScript1 (ES1) kenmerk.
ES1 (JavaScript 1997) word ten volle ondersteun in alle blaaiers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |
Sintaksis
Date.prototype.name = value
Waarskuwing
Jy word nie aangeraai om die prototipe van 'n voorwerp wat jy nie beheer nie te verander nie.
Jy moet nie die prototipe van ingeboude JavaScript-datatipes verander soos:
- Getalle
- Snare
- Skikkings
- Datums
- Booleans
- Funksie
- Voorwerpe
Verander net die prototipe van jou eie voorwerpe.
Die prototipe Eiendom
Die JavaScript- prototype
eienskap laat jou toe om nuwe eienskappe by voorwerpe te voeg:
Voorbeeld
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";