2011-07-04 8 views
1

자바 스크립트에서 OOP를 처음 사용합니다. 메소드를 오버라이드하고 싶을 때 제대로 이해하지 못합니다. 나는 아래에서 나의 문제에 대한 모범을 보였다. 또한자바 스크립트 메소드 오버라이드

function myGeometryObject(r, x, y){ 

    this.r = r; 
    this.x = x; 
    this.y = y; 

    var OBJ = this; 

    this.returnArea = function(){ 
     return 'wrong override'; 
    } 
} 

function myRectangle(r, x, y){ 
    myGeometryObject.call(this, r, x, y); 
} 
myRectangle.prototype = new myGeometryObject(); 

myRectangle.prototype.returnArea = function(){ 
    return 'right override';//I want JS to use this method 
} 
var rectangle = new myRectangle(0, 5, 5); 
alert(rectangle.returnArea()); 

답변

8
http://jsfiddle.net/sRyQA/

문제는

this.returnArea = function(){ 
    return 'wrong override'; 
} 

가 (새 MyRectangle 인스턴스 부모의 생성자를 호출 제대로만큼) 특정 예를의 속성을 설정하는 것입니다 모든 상속 된 메서드를 "오버라이드"합니다.

귀하의 프로토 타입 체인은 다음과 같습니다 : 인스턴스의 retunArea 방법을 사용하여 MyGeometryObject 생성자에서 할당 하나는 프로토 타입의 하나입니다

+------------------+  +------------------+  +------------------+ 
| MyRectangle  |  | MyRectangle  |  | MyGeometry  | 
| instance   |------->| prototype  |------->| prototype  | 
|     |  |     |  |     | 
| wrong returnArea |  | right returnArea |  |     | 
+------------------+  +------------------+  +------------------+ 
          (MyGeometry instance) 

당신이 덮어 쓰기 한 것입니다.

하지만 당신은 프로토 타입 체인에 앞서 올 것이다 권리로, returnArea 방법을 MyGeometryObject의 다음 prototype

function MyGeometryObject(r, x, y) { 
    this.r = r; 
    this.x = x; 
    this.y = y;  
} 

MyGeometryObject.prototype.returnArea = function(){ 
    return 'wrong override'; 
} 

가 작동이 방법을 할당하는 경우 :

+------------------+  +------------------+  +------------------+ 
| MyRectangle  |  | MyRectangle  |  | MyGeometry  | 
| instance   |------->| prototype  |------->| prototype  | 
|     |  |     |  |     | 
|     |  | right returnArea |  | wrong returnArea | 
+------------------+  +------------------+  +------------------+ 
          (MyGeometry instance) 

또한 노트 :

  • 생성자 함수 이름은 대문자로 시작해야합니다. 당신이 MyRectangle의 프로토 타입이 방법을 설정하면
  • , 당신은 또한 MyRectangle로 다시 constructor 속성을 설정해야합니다

    MyRectangle.prototype = new MyGeometryObject(); 
    MyRectangle.prototype.constructor = MyRectangle; 
    
+0

또 다른 방법은'myRectangle' 생성자의 방법을 덮어 쓰기하는 것입니다 (적용 후 myGeometryObject 생성자에 대한 인수). http://jsfiddle.net/sRyQA/2/ – katspaugh

+0

@Felix KLing MyRectangle.prototype.constructor = MyRectangle의 기능은 무엇입니까? – einstein

+0

@ Woho87 : 프로토 타입의'constructor' 속성을'MyRectangle'으로 설정합니다. 이 속성은 프로토 타입이 프로토 타입 인 함수를 항상 가리 킵니다. 보십시오 :'function Foo() {}; console.dir (Foo.protoype);'. –

관련 문제