JavaScript Prototipo di data
Esempio
Crea un nuovo metodo date che dia all'oggetto date una proprietà nome-mese chiamata 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"};
}
Crea un oggetto Date, quindi chiama il metodo myMonth:
const d = new Date();
let month = d.myMonth();
Definizione e utilizzo
prototype
ti consente di aggiungere nuove proprietà e metodi alle date.
prototype
è una proprietà disponibile con tutti gli oggetti JavaScript.
Supporto browser
prototype
è una funzione ECMAScript1 (ES1).
ES1 (JavaScript 1997) è completamente supportato in tutti i browser:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |
Sintassi
Date.prototype.name = value
Avvertimento
Non è consigliabile modificare il prototipo di un oggetto che non controlli.
Non dovresti modificare il prototipo dei tipi di dati JavaScript integrati come:
- Numeri
- stringhe
- Matrici
- Date
- booleani
- Funzione
- Oggetti
Cambia solo il prototipo dei tuoi oggetti.
La proprietà prototipo
La proprietà JavaScript prototype
consente di aggiungere nuove proprietà agli oggetti:
Esempio
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";