English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
PrototipoEs un mecanismo, a través del cual los objetos JavaScript heredan características unos de otros.
En el capítulo anterior, aprendimos cómo usarConstructor:
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");Prueba para ver‹/›
También hemos aprendidoNo se puedeAñadir nuevas propiedades al constructor de objetos existentes:
User.weapon = "Sword";Prueba para ver‹/›
Para agregar nuevas propiedades al constructor, debe agregarlas al constructor mismo:
function User(fname, lname, age, loc) { this.firstName = fname; this.lastName = lname; this.age = age; this.location = loc; this.weapon = "Sword"; }Prueba para ver‹/›
A veces queremos agregar nuevas propiedades y métodos a un constructor más adelante, que se compartirán entre todos los objetos (ejemplos). La respuesta es el objetoPrototipo。
La propiedad prototype permite agregar atributos y métodos a los constructores.
En este ejemplo, la propiedad prototype permite agregar nuevos atributos al constructor de User:
function User(fname, lname, age, loc) { this.firstName = fname; this.lastName = lname; this.age = age; this.location = loc; } User.prototype.weapon = "Sword";Prueba para ver‹/›
En este ejemplo, la propiedad prototype permite agregar nuevos métodos al constructor de User:
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; };Prueba para ver‹/›
Atención:Sólo modifique su prototipo propio. No modifique el prototipo estándar (interno) de los objetos JavaScript.