2015-01-15 6 views
1

에서 부모의 메소드를 호출하는 방법 : Uncaught TypeError: Cannot read property 'call' of undefined나는 방법 pranet 전화를 시도하고이 오류 받고 있어요 아이

http://jsfiddle.net/5o7we3bd/

function Parent() { 
    this.parentFunction = function(){ 
     console.log('parentFunction'); 
    } 
} 
Parent.prototype.constructor = Parent; 

function Child() { 
    Parent.call(this); 
    this.parentFunction = function() { 
     Parent.prototype.parentFunction.call(this); 
     console.log('parentFunction from child'); 
    } 
} 
Child.prototype = Object.create(Parent.prototype); 
Child.prototype.constructor = Child; 

var child = new Child(); 
child.parentFunction(); 

답변

3

당신은에 "parentFunction"을 붙이려는 건 아니죠을 "부모"프로토 타입. "부모"생성자는 인스턴스에에 "parentFunction"속성을 추가하지만 프로토 타입에는 함수로 표시되지 않습니다.

생성자 함수에서 thisnew을 통해 호출 한 결과로 생성 된 새 인스턴스를 참조합니다. 인스턴스에 메소드를 추가하는 것은 좋은 일이지만 생성자 프로토 타입에 메소드를 추가하는 것과 완전히 같지 않습니다.

function Child() { 
    Parent.call(this); 
    var oldParentFunction = this.parentFunction; 
    this.parentFunction = function() { 
     oldParentFunction.call(this); 
     console.log('parentFunction from child'); 
    } 
} 
+0

대 :

는 "부모"생성자가 추가 "parentFunction는"당신이 참조를 저장할 수에 액세스하려면

. 그것은 작동합니다! 설명 해줘서 고마워. 나는 OOP 자바 스크립트에 새로운입니다. – user1561346

관련 문제