2014-05-12 4 views
1

각 차트 응용 프로그램에 여러 개의 Raphael 개체로 구성된 논리 개체가 있습니다. 예를 들어 데이터 요소는 원과 캡션으로 구성 될 수 있습니다.Raphael.st의 하위 클래스는 어떻게합니까?

모든 개체를 하나의 개체로 처리 할 수 ​​있고 또한 어떤 Raphael 요소가 어떤 논리 개체에 속해 있는지 확인할 수 있기를 원합니다 (예 : 논리 요소의 컨텍스트에있는 요소에 대해 마우스 클릭을 처리하려면 그것이 속한).

Raphael.st (즉, Raphael 세트)의 서브 클래스를 만들고 포함 된 논리 오브젝트에 element.data ("object")를 설정하기 위해 push 메소드를 대체 할 수 있기를 바랍니다. 코드의 다른 곳에서

, 나 (I이 스택 오버플로 없음) 다음 서브 클래스에있어서 사용 base.prototype가 null 때문에

/** 
* Utility function to help subclassing 
* @param base 
* @param sub 
*/ 
function subclass(base, sub) { 
    // Avoid instantiating the base class just to setup inheritance 
    // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create 
    // for a polyfill 
    sub.prototype = Object.create(base.prototype); 
    // Remember the constructor property was set wrong, let's fix it 
    sub.prototype.constructor = sub; 
    // In ECMAScript5+ (all modern browsers), you can make the constructor property 
    // non-enumerable if you define it like this instead 
    Object.defineProperty(sub.prototype, 'constructor', { 
     enumerable: false, 
     value: sub 
    }); 
} 

그러나, 이러한 방법은 예외가 발생된다 때베이스 = 라파엘.

자바 스크립트에서 서브 클래 싱이 실제로 어떻게 작동하는지에 대해 사과드립니다. 다른 곳에서 맹목적으로 코드를 복사하는 것이 이상적이지는 않지만, 아직 이해할 수있는 설명을 찾지 못했습니다!

Raphael.st를 서브 클래스 화하는 방법을 누군가에게 알려줄 수 있습니까? 그리고/또는 나 자신을 위해 어떻게 작동하는지 설명 할 수있는 설명의 방향으로 나를 가리키게 할 수 있습니까?

답변

1

Raphael.set은 Raphael이 기대하지 않기 때문에 하위 클래스로 만드는 것은 좋지 않습니다. 적절한 서브 클래스 테스트를 실패 의미

if (element.constructor == R.st.constructor) 

: 예를 들어,이 일련의 처리 여부를 알 필요 여부 라파엘 코드의 많은과 같은 코드를 사용합니다.

계속 진행하고 싶을 때 (시도한 것처럼 속성이나 함수 이름이 충돌하지 않습니다!), 답을 찾았습니다.

Raphael이 일반적인 규칙을 따르지 않기 때문에 하위 클래스 함수를 수정해야합니다. Raphael.st는 클래스가 아니므로 클래스의 프로토 타입입니다. 다음과 같이 서브 클래스의 방법은 그러므로 수정해야이 다른 사람 도움

/** 
* @param paper Raphael Paper 
*/ 
var MySet = function(paper) { 
Raphael.st.constructor.call(this); 
// Without this, Raphael does not recognise MySet objects as sets 
// because it tests constructor value using == instead of instanceof 
this.constructor = Raphael.st.constructor; 
// Cheat!! Copied this code from Raphael Paper.set() 
this.paper = paper; 
}; 

subclass(Raphael.st, MySet); 

희망 :

여기
function subclass(base, sub) { 
// Avoid instantiating the base class just to setup inheritance 
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create 
// for a polyfill 
sub.prototype = Object.create(base.prototype ? base.prototype : base); 
// Remember the constructor property was set wrong, let's fix it 
sub.prototype.constructor = sub; 
// In ECMAScript5+ (all modern browsers), you can make the constructor property 
// non-enumerable if you define it like this instead 
Object.defineProperty(sub.prototype, 'constructor', { 
    enumerable: false, 
    value: sub 
}); 
} 

이 서브 클래스의 생성자입니다!

관련 문제