2014-05-09 4 views
-1

수퍼 클래스에는 '컨테이너'속성이 있습니다.자바 스크립트 프로토 타입 상속 버그

하위 클래스가 수퍼 클래스에서 상속하는 경우 'container'속성은 하위 클래스간에 공유됩니다.

각 서브 클래스가 자신의 모든 특성과 함께 수퍼 클래스의 자체 사본을 갖고있는 것을 어떻게 구현합니까?

var a = function() { 
}; 

a.prototype.ax = function() { 
    this.container = []; 
} 

var b = function() { 
a.call(this); 
} 

b.constructor = b; 
b.prototype = Object.create(a.prototype); 

b.prototype.ax = function() { 
a.prototype.ax(); 
    this.container.push('b'); 
} 

var c = function() { 
a.call(this); 
} 

c.constructor = c; 
c.prototype = Object.create(a.prototype); 

c.prototype.ax = function() { 
    a.prototype.ax(); 
    this.container.push('c'); 
} 


var bi = new b(); 
var ci = new c(); 

bi.ax(); 
ci.ax(); 

// why bi container gets overriden? 
console.log(bi.container); 

JS Fiddle

답변

0

당신의 문제가 여기에 있습니다 :

b.prototype.ax = function() { 
    a.prototype.ax(); 
    this.container.push('b'); 
} 

는 슈퍼 클래스의 함수를 호출하려면 지금처럼해야합니다

b.prototype.ax = function() { 
    a.prototype.ax.call(this); 
    this.container.push('b'); 
} 

그렇지 않으면 당신은 단순히 ax를 호출 문맥으로 a.prototype (값 this).

관련 문제