2010-02-19 12 views
6

Sono un neofita dell'eredità prototipale, quindi sto cercando di capire il modo "giusto". Ho pensato che avrei potuto fare questo:Eredità prototipale: puoi concatenare Object.create?

if (typeof Object.create !== 'function') { 
    Object.create = function (o) { 
     function F() {} 
     F.prototype = o; 
     return new F(); 
    }; 
} 

var tbase = {}; 

tbase.Tdata = function Tdata() {}; 

tbase.Tdata.prototype.say = function (data) { 
    console.log(data); 
}; 

var tData = new tbase.Tdata(); 

tbase.BicData = Object.create(tData); 

tbase.BicData.prototype.say = function (data) { 
    console.log("overridden: " + data) 
}; 

tbase.BicData.prototype.shout = function (data, temp) { 
    console.log("SHOUT: " + data + ", " + temp) 
}; 

var test = new tbase.BicData(); 

tData.say("test1"); 
test.say("test2"); 
test.shout("test3", "hope"); 

if (typeof Object.create !== 'function') { 
    Object.create = function (o) { 
     function F() {} 
     F.prototype = o; 
     return new F(); 
    }; 
} 

var tbase = {}; 

tbase.Tdata = function Tdata() {}; 

tbase.Tdata.prototype.say = function (data) { 
    console.log(data); 
}; 

var tData = new tbase.Tdata(); 

tbase.BicData = Object.create(tData); 

tbase.BicData.prototype.say = function (data) { 
    console.log("overridden: " + data) 
}; 

tbase.BicData.prototype.shout = function (data, temp) { 
    console.log("SHOUT: " + data + ", " + temp) 
}; 

var test = new tbase.BicData(); 

tData.say("test1"); 
test.say("test2"); 
test.shout("test3", "hope"); 

Ma invece ottengo "tbase.BicData.prototype è indefinito"

In Java parlare, quello che voglio è avere TDATA come un testo standard ' interfaccia ', BicData per essere un'implementazione di quello, e quindi per creare un'istanza di oggetti da esso.

Dove sto andando male?

risposta

8

Il problema è che tbase.BicData è un oggetto (tbase.BicData = Object.create(tData);) e la proprietà prototype deve essere utilizzata sulle funzioni di costruzione.

Approfittando del metodo Object.create, vorrei fare qualcosa di simile:

var tbase = {}; 

tbase.Tdata = { 
    say : function (data) { 
    console.log(data); 
    } 
}; 

tbase.BicData = Object.create(tbase.Tdata); 

tbase.BicData.say = function (data) { 
    console.log("overridden: " + data) 
}; 

tbase.BicData.shout = function (data, temp) { 
    console.log("SHOUT: " + data + ", " + temp) 
}; 

var test = Object.create(tbase.BicData); 
var tData = Object.create(tbase.Tdata); 

tData.say("test1"); // test1 
test.say("test2"); // overridden: test2 
test.shout("test3", "hope"); // SHOUT: test3, hope 
+3

+1 ho cancellato la mia risposta, lei ha ragione :) – mck89

+0

Questo sembra buono! Grazie :) – robinhowlett

+1

Penso che la maggior parte della confusione dell'OP verrebbe evitata se l'OP non avesse mixato 'new' e' Object.create'. Dico sceglierne uno e seguitelo. –