2010-02-19 22 views
6

Jestem nowy w dziedziczeniu prototypowym, więc staram się zrozumieć "właściwy" sposób. Myślałem, że mogę to zrobić:Dziedziczenie prototypowe: czy można połączyć obiekt 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"); 

Ale zamiast ja dostać „tbase.BicData.prototype jest niezdefiniowany

W Javie mówić, co chcę to mieć Tdata jako boilerplate ' interface ', BicData za implementację tego, a następnie za utworzenie obiektów z niego.

Gdzie się mylę?

Odpowiedz

8

Problem polega na tym, że obiekt tbase.BicData jest obiektem (tbase.BicData = Object.create(tData);), a właściwość prototype powinna być używana w funkcjach konstruktora.

Wykorzystując metody Object.create, chciałbym zrobić coś takiego:

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 Usunąłem moją odpowiedź, masz rację :) – mck89

+0

To wygląda dobrze! Dziękuję :) – robinhowlett

+1

Myślę, że większość zamieszania OP byłaby unikana, gdyby OP nie mieszał "nowych" i "Object.create". Mówię, wybierz jeden i trzymaj się go. –

Powiązane problemy