JavaScript-datum prototype
Voorbeeld
Maak een nieuwe datummethode die het date-object een eigenschap maandnaam geeft met de naam 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"};
}
Maak een Date-object en roep vervolgens de myMonth-methode aan:
const d = new Date();
let month = d.myMonth();
Definitie en gebruik
prototype
stelt u in staat om nieuwe eigenschappen en methoden aan datums toe te voegen.
prototype
is een eigenschap die beschikbaar is bij alle JavaScript-objecten.
Browserondersteuning
prototype
is een ECMAScript1 (ES1)-functie.
ES1 (JavaScript 1997) wordt volledig ondersteund in alle browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |
Syntaxis
Date.prototype.name = value
Waarschuwing
Het wordt afgeraden om het prototype van een object dat u niet onder controle heeft te wijzigen.
U moet het prototype van ingebouwde JavaScript-gegevenstypen zoals:
- Cijfers
- Snaren
- arrays
- data
- Booleans
- Functie
- Voorwerpen
Verander alleen het prototype van uw eigen objecten.
Het prototype eigendom
Met de JavaScript- prototype
eigenschap kunt u nieuwe eigenschappen aan objecten toevoegen:
Voorbeeld
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";