2015-01-31 3 views
0

기본적으로 instanceof Something === true이있는 기능을 원합니다.맞춤 "클래스"기능

그래서이되도록 MySpecialKindOfFunction 같은 :

if (theFunction instanceof MySpecialKindOfFunction) 

내가 작업없이 함수의 프로토과 생성자 설정을 시도했습니다.

+0

서브 클래 싱 원주민이 문제가 :

if(interface.constructor !== Interface) { 

는이 작업을 수행 할 수있는 클래스를위한 확장하십시오. [이 기사] (http://speakingjs.com/es5/ch28.html) 또는 다른 곳을 살펴보십시오. 그것은 ECMA6에서 가능할 수도 있지만, 나는 그것에 대해 조사하지 않았습니다. – hon2a

답변

0

어쩌면 내가 당신의 질문을 이해하지 못 하겠지만 당신이 달성하고자하는이 종류입니까?

// Static class method. 
Interface.ensureImplements = function(object) { 
    if(arguments.length < 2) { 
     throw new Error("Function Interface.ensureImplements called with " + 
     arguments.length + " arguments, but expected at least 2."); 
    } 
    for(var i = 1, len = arguments.length; i < len; i++) { 
     var interface = arguments[i]; 
     if(interface.constructor !== Interface) { 
      throw new Error("Function Interface.ensureImplements expects arguments" 
      + " two and above to be instances of Interface."); 
     } 
     for(var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) { 
      var method = interface.methods[j]; 
      if(!object[method] || typeof object[method] !== 'function') { 
       throw new Error("Function Interface.ensureImplements: object " 
       + "does not implement the " + interface.name 
       + " interface. Method " + method + " was not found."); 
      } 
     } 
    } 
}; 

이 코드를 사용하여 함수가 인터페이스 유형인지 테스트합니다. 키 코드는 다음과 같습니다

function Item() { 

}; 

function Picture() { 
    Item.call(this); // Call to superClass constructor with subclass instance 
}; 


Picture.prototype = new Item(); 
Picture.prototype.constructor = Picture; 

var picture = new Picture(); 
if(picture instanceof Item){ 
    alert("True"); 
} else { 
    alert(false); 
} 
+0

나는 instanceof SomethingElse 인 함수를 원한다. 즉, Object 대신 Function을 서브 클래 싱하는 것입니다. –

+0

답변을 업데이트합니다. 이 예제에서 Picture는 Item의 하위 클래스입니다. extension 함수는 원하는 위치에있을 수 있습니다. – Scandinave

+0

클래스가 함수 여야합니다. 그것이 함수의 하위 클래스가되어야 함을 의미합니다. 즉, 일부 var myVar, 호출 할 수 있습니다 : myVar(), 그리고 또한 instanceof 일부 "하위 클래스"함수입니다. –

관련 문제