2010-02-19 6 views
6

프로토 타입 상속에 익숙하지 않으므로 '올바른'방식을 이해하려고합니다. 나는이 작업을 수행 할 수 있다고 생각 :Prototypal inheritance : 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"); 

하지만 그 대신 나는 자바에서

가, 내가 원하는 것은 ' 을 가지고 상용구로 TDATA이다 " tbase.BicData.prototype이이 정의되지"GET 인터페이스 ', BicData 그 구현 및 다음 개체를 인스턴스화 할 수 있습니다.

어디로 잘못 가고 있습니까?

답변

8

문제는 tbase.BicData이 개체 (tbase.BicData = Object.create(tData);)이고 생성자 함수에 prototype 속성을 사용해야한다는 것입니다.

Object.create 방법을 활용, 나는 이런 식으로 뭔가를 할 것이다 : 나는 내 대답을 삭제 한

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, 당신은 : 맞아요 – mck89

+0

이 좋아 보인다! 고맙습니다. – robinhowlett

+1

OP가 'new'와 'Object.create'를 섞어 놓지 않으면 대부분의 OP 혼동을 피할 수 있다고 생각합니다. 나는 하나를 골라서 붙잡는다. –