Prototyp data JavaScript
Příklad
Vytvořte novou metodu data, která dá objektu date vlastnost název měsíce s názvem 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"};
}
Vytvořte objekt Date a poté zavolejte metodu myMonth:
const d = new Date();
let month = d.myMonth();
Definice a použití
prototype
umožňuje přidávat k datům nové vlastnosti a metody.
prototype
je vlastnost dostupná u všech objektů JavaScriptu.
Podpora prohlížeče
prototype
je funkce ECMAScript1 (ES1).
ES1 (JavaScript 1997) je plně podporován ve všech prohlížečích:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
Date.prototype.name = value
Varování
Nedoporučuje se měnit prototyp objektu, který neovládáte.
Neměli byste měnit prototyp vestavěných datových typů JavaScriptu, jako jsou:
- čísla
- Struny
- Pole
- Termíny
- Booleans
- Funkce
- Objekty
Měňte pouze prototyp vlastních objektů.
Vlastnost prototypu
Vlastnost JavaScript prototype
vám umožňuje přidávat nové vlastnosti k objektům:
Příklad
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";