Javascript eredità domanda
-
28-10-2019 - |
Domanda
Perché la Versione 2 nel codice riportato di seguito non produce lo stesso risultato come la Versione 1 ?
function person(name) {
this.name = name;
}
function student(id, name) {
this.id = id;
// Version 1
//this.inherit_from_person = person;
//this.inherit_from_person(name);
// Version 2
person(name);
}
s = new student(5, 'Misha');
document.write(s.name); // Version 1 => Misha
// Version 2 => undefined
Soluzione
Quando chiami person(name)
Viene chiamato con this
vincolato all'oggetto globale, quindi è solo l'impostazione window.name = "Misha"
. Tu vuoi person.call(this, name)
per legarlo esplicitamente a destra this
.
Altri suggerimenti
Mi sembra che si sta cercando di implementare l'ereditarietà di prototipi.Qui di seguito è un esempio classico, anche se non molto usato.Eredità complessa è non solo necessario, in javascript, di solito una singola istanza è tutto ciò che è necessario.Se più istanze richiesti, il modulo schema può essere utilizzato con le chiusure per la condivisione di metodologie e di proprietà e anche per fornire privato e priveliged membri.
// Person is the "base class"
function Person(name) {
this.setName(name);
}
// Use setters and getters so properties are
// added appropriately.
Person.prototype.setName = function(name) {
this.name = name;
}
// Add Person methods
Person.prototype.getName = function() {
return this.name;
}
// Student inherits from Person and also has
// its own methods
function Student(name, id) {
this.setId(id);
this.setName(name);
}
// To inherit from Person, Student.prototype should
// be an instance of Person
Student.prototype = new Person();
// Add Student methods
Student.prototype.setId = function(id) {
this.id = id;
}
Student.prototype.getId = function() {
return this.id;
}
var p0 = new Student('Sally', '1234');
var p1 = new Person('James');
alert('p0\'s id is ' + p0.id + ' and name is: ' + p0.name);
alert('p1\'s name is: ' + p1.name);
alert('Is p0 a student? ' + (p0 instanceof Student));
alert('Is p1 a student? ' + (p1 instanceof Student));
Si noti che il instanceof l'operatore non è molto affidabile, ma funziona bene nel caso di cui sopra.Anche tutti i metodi e le proprietà del pubblico, in modo facilmente sopra scritto.