2016-09-27 3 views
1

상속 된 개체를 제대로 재정의 할 수없고 여기서 손을 얻을 수 있는지 궁금합니다. 벌써 3 일 동안 붙어서. 내가 'New Location' 얻을 bobStu.serviceArea();을 실행할 때JS 중첩 된 상속

내가 bobStu.getValue();을 실행할 때 나는 'Old Location'

나는 방법 아래이 bobStu.getValue();을 통과하고있어 얻을, 다음

function Person() { 
    function getValue(){ 
     serviceArea(); 
    } 

    function serviceArea() { 
     alert('Old Location'); 
    } 

    return { 
     getValue: getValue, 
     serviceArea: serviceArea 
    } 
} 

function Student() {}; 
Student.prototype = new Person(); 
Student.prototype.serviceArea = function() { alert('New Location'); }; 
var bobStu = new Student(); 

말을 그 재정의 된 메소드를 호출해야하지만 그렇게 할 수는 없습니다. getValue()이 이전 serviceArea()을 호출하는 이유를 설명 할 수 있습니까? 어떻게 제대로 할 수 있을까요?

이 글을 여러 번 준비하고 그것은 나에게 뭔가를 말하고있는 것 같은 느낌하지만 난 얻을 수없는 것을 너무 번제 해요 봤는데 그것이 :(단지 serviceArea()를 사용 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Namespace

+0

'Person'은 클래식 생성자가 아닌 팩토리 함수이며 범위 지정은 속성을 고려하지 않습니다. – Bergi

+0

이 스레드에서 답변을 찾을 수 있습니다. http://stackoverflow.com/questions/12183011/javascript-redefine-and-override-existing-function-body useful. – Rosa

답변

3

만 기능 serviceArea을 말한다 Person의 범위에서 정의 :.

function Person() { 
    function getValue(){ 
     serviceArea(); // this... 
    } 

    // ...always refers to this, independent of the object you're constructing 
    function serviceArea() { 
     alert('Old Location'); 
    } 

    // also note this: 
    this.getValue = getValue; 
    this.serviceArea = serviceArea; 
} 

사용하면 서브 클래스에 의해 구현 된 serviceArea 방법을 사용하려면 대신하는 경우 this.serviceArea()

또한 생성자는 값을 반환하지 않아야합니다. 대신 값을 값에 직접 첨부하십시오.