2010-12-23 3 views
5

후 나는이 흥미로운 문제를 발견했습니다 :이 제대로 상속

function a() { this.aprop = 1; } 
function b() { this.bprop = 2; } 
b.prototype = new a(); // b inherits from a 
var x = new b(); // create new object with the b constructor 
assert(x.constructor == b); // false 
assert(x.constructor == a); // true 

지금까지 내가 아는 한, x.constructorb해야하지만, 실제로의 a 때 프로토 타입을 통해 a에서 b 상속? 내 생성자를 망치지 않고 a에서 상속받을 수있는 방법이 있습니까?

답변

3

b.prototype.constructor은 3 행에 new a().constructor으로 지정 되었기 때문입니다. 이 속성은 다음 줄에서 다시 변경할 수 있습니다.

function a() { this.aprop = 1; } 
function b() { this.bprop = 2; } 
b.prototype = new a(); // b inherits from a 
b.prototype.constructor = b; // <-- add this 
var x = new b(); // create new object with the b constructor 
assert(x.constructor == b); // false 
assert(x.constructor == a); // true 
+0

감사합니다! 이 두 줄을 수행하는 빠른'함수 (목표, 부모) '를 작성하는 것이 가능하고 좋은 아이디어일까요? –

+0

@Delan : 물론 가능합니다. –

+0

완벽하게 작동합니다. 앤디에게 다시 한 번 감사드립니다. –