English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
PrototipoÈ un meccanismo tramite il quale gli oggetti JavaScript ereditano le caratteristiche l'uno dall'altro.
Nell'ultimo capitolo, abbiamo imparato come utilizzareCostruttore:
function User(fname, lname, age, loc) { this.firstName = fname; this.lastName = lname; this.age = age; this.location = loc; } var Seagull = new User("Seagull", "Anna", 22, "New Delhi"); var tarush = new User("Tarush", "Balodhi", 34, "Bihar");Testa e guarda‹/›
Abbiamo anche scopertoNon è possibileAggiungi la nuova proprietà al costruttore dell'oggetto esistente:
User.weapon = "Sword";Testa e guarda‹/›
Per aggiungere nuove proprietà al costruttore, è necessario aggiungerle all'interno del costruttore:
function User(fname, lname, age, loc) { this.firstName = fname; this.lastName = lname; this.age = age; this.location = loc; this.weapon = "Sword"; }Testa e guarda‹/›
A volte possiamo voler aggiungere nuovi attributi e metodi al costruttore in seguito, che saranno condivisi tra tutti gli oggetti (esempi). La risposta è l'oggettoPrototipo.
L'attributo prototype ti permette di aggiungere attributi e metodi al costruttore.
In questo esempio, l'attributo prototype ti permette di aggiungere nuovi attributi al costruttore User oggetto:
function User(fname, lname, age, loc) { this.firstName = fname; this.lastName = lname; this.age = age; this.location = loc; } User.prototype.weapon = "Sword";Testa e guarda‹/›
In questo esempio, l'attributo prototype ti permette di aggiungere nuovi metodi al costruttore User oggetto:
function User(fname, lname, age, loc) { this.firstName = fname; this.lastName = lname; this.age = age; this.location = loc; } User.prototype.fullName = function() { return this.firstName + " " + this.lastName; };Testa e guarda‹/›
Attenzione:Modifica solo il tuo prototipo. Non modificare il prototipo degli oggetti JavaScript (standard) integrati.