Skip to content

Instantly share code, notes, and snippets.

@jherax
Last active September 24, 2018 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jherax/457b06131cf48af92cda to your computer and use it in GitHub Desktop.
Save jherax/457b06131cf48af92cda to your computer and use it in GitHub Desktop.
JavaScript OOP: Herencia y Prototipos
//definimos el constructor del objeto base y
//establecemos las propiedades por instancia
function Person (name, age) {
"use strict";
this.name = name || "unnamed";
this.age = +age || 0;
}
//definimos el prototipo del objeto base
//estableciendo las propiedades compartidas
//(delegación automática)
Person.prototype = {
setAge: function (age) {
this.age = +age || 0;
},
speak: function (message) {
message = message ? ", " + message : "";
return "Hi, my name is " + this.name + message;
}
};
//definimos el constructor de la "subclase" y
//establecemos las propiedades por instancia
function Teacher (name) {
"use strict";
this.name = name;
this.subjects = [];
}
//heredamos del objeto base
//mediante instanciación
Teacher.prototype = new Person;
//corregimos el constructor
//porque fue sobrescrito por la herencia
Teacher.prototype.constructor = Teacher;
//extendemos el prototipo de la "subclase"
//estableciendo las propiedades compartidas
//(delegación automática)
Teacher.prototype.addSubject = function (matter) {
if (matter) this.subjects.push(matter);
};
//@override (sobrescribe toString)
Person.prototype.toString = function() {
return "[Person Object]";
}
//@override (sobrescribe toString)
Teacher.prototype.toString = function() {
return "[Teacher Person]";
};
//instancias de Person y Teacher
var luis = new Person("Luis"),
juan = new Teacher("Juan");
//invoca el método definido en el prototipo de Teacher
juan.addSubject("Design Patterns");
//invoca un método definido en el prototipo de Person
juan.setAge(32);
console.log(luis.toString(), luis); //[Person Object]
console.log(juan.toString(), juan); //[Teacher Person]
//vemos el prototipo de juan
Object.getPrototypeOf(juan);
juan instanceof Teacher;
Teacher.prototype.isPrototypeOf(juan);
//true, porque Teacher.prototype está en Object.getPrototypeOf(juan)
juan instanceof Person;
Person.prototype.isPrototypeOf(juan);
//true, porque Person.prototype está en Object.getPrototypeOf(juan)
juan instanceof Object;
Object.prototype.isPrototypeOf(juan);
//true, porque Object.prototype está en Object.getPrototypeOf(juan)
juan instanceof Date;
Date.prototype.isPrototypeOf(juan);
//false, porque Date.prototype no está en Object.getPrototypeOf(juan)
@jherax
Copy link
Author

jherax commented May 26, 2015

Vea el artículo completo en: POO en JavaScript – Prototipos

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment