Sto progettando una gerarchia di classi in JavaScript. Funziona bene finora, ma non riesco a vedere come determinare se un oggetto è una "istanza" di una classe genitore. Esempio:javascript oop, instanceof e classe base
function BaseObject(name){
this.name = name;
this.sayWhoAmI = function(){
console.log(this.name + ' is a Derivation1 : ' + (this instanceof Derivation1));
console.log(this.name + ' is a Derivation2 : ' + (this instanceof Derivation2));
console.log(this.name + ' is a BaseObject : ' + (this instanceof BaseObject));
};
}
function Derivation1(){
BaseObject.apply(this, ['first derivation']);
}
function Derivation2(){
BaseObject.apply(this, ['second derivation']);
}
var first = new Derivation1();
var second = new Derivation2();
first.sayWhoAmI();
tronchi questo:
first derivation is a Derivation1 : true
first derivation is a Derivation2 : false
first derivation is a BaseObject : false
mentre second.sayWhoAmI();
registra questo:
second derivation is a Derivation1 : false
second derivation is a Derivation2 : true
second derivation is a BaseObject : false
mi sento come sia oggetto first
e second
dovrebbe avere dire che sono istanze di BaseObject
.
Comprendo che JavaScript non può essere creato per questo, ma mi chiedo se c'è un modo per farlo.
chiamando Solo 'Base.apply (...)' non lo fa l'installazione eredità. Devi impostare correttamente il prototipo. Vedi: http://jsfiddle.net/fkling/wJE6s/. Dai anche un'occhiata a questa domanda per una spiegazione: http: // StackOverflow.it/questions/3145700/javascript-inheritance-instanceof-not-working? rq = 1 –
Felix dovresti scrivere questo come risposta, questo è esattamente ciò di cui ho bisogno e il tuo violino lo dimostra semplicemente. Non permettere a qualcun altro di rubare la tua reputazione! – Johnny5
Concordato che dovrebbe aggiungere una risposta, ma probabilmente non è preoccupato di aumentare il suo rappresentante dello 0,01%! – jahroy