ProgramingTip

Javascript 클래스가 다른 클래스를 상속하는지 확인하는 방법 (obj를 생성하지 않고)?

bestdevel 2020. 11. 13. 23:51
반응형

Javascript 클래스가 다른 클래스를 상속하는지 확인하는 방법 (obj를 생성하지 않고)?


예 :

function A(){}
function B(){}
B.prototype = new A();

클래스 B가 클래스 A를 상속하는지 어떻게 확인할 수 있습니까?


시도 해봐 B.prototype instanceof A


직접 상속을 테스트 할 수 있습니다.

B.prototype.constructor === A

간접 상속을 테스트 후 사용할 수 있습니다.

B.prototype instanceof A

(이 두 번째 솔루션은 Nirvana Tikku가 처음 제공했습니다)


2017 년으로 돌아 가기 :
그것이 당신에게 효과가 있는지 확인하십시오

A.isPrototypeOf(B)

개는 : 참고 instanceof여러 실행 시나리오 / 창을 사용하는 경우 예상대로 작업을 수행합니다. §§을 참조하십시오 .


또한 https://johnresig.com/blog/objectgetprototypeof/에 따라 다음과 같은 대체 구현입니다 instanceof.

function f(_, C) { // instanceof Polyfill
  while (_ != null) {
    if (_ == C.prototype)
      return true;
    _ = _.__proto__;
  }
  return false;
}

클래스를 직접 확인하도록 수정하면 다음과 같은 이점이 있습니다.

function f(ChildClass, ParentClass) {
  _ = ChildClass.prototype;
  while (_ != null) {
    if (_ == C.prototype)
      return true;
    _ = _.__proto__;
  }
  return false;
}


사이드 노트

instanceof경우에 자체 검사 obj.proto이고 f.prototype, 따라서 :

function A(){};
A.prototype = Array.prototype;
[]instanceof Array // true

과 :

function A(){}
_ = new A();
// then change prototype:
A.prototype = [];
/*false:*/ _ instanceof A
// then change back:
A.prototype = _.__proto__
_ instanceof A //true

과 :

function A(){}; function B(){};
B.prototype=Object.prototype;
/*true:*/ new A()instanceof B 

같지 않으면 proto는 수표에서 proto의 proto로 바뀐 ​​다음 proto의 proto로 바뀝니다. 그러므로:

function A(){}; _ = new A()
_.__proto__.__proto__ = Array.prototype
g instanceof Array //true

과:

function A(){}
A.prototype.__proto__ = Array.prototype
g instanceof Array //true

과:

f=()=>{};
f.prototype=Element.prototype
document.documentElement instanceof f //true
document.documentElement.__proto__.__proto__=[];
document.documentElement instanceof f //false

나는 Simon B.prototype = new A()이 그의 질문에서 의미하지 않았다고 생각합니다. 이것은 확실히 JavaScript에서 프로토 타입을 연결하는 방법이 아니기 때문입니다.

B가 A를 확장한다고 가정하면 Object.prototype.isPrototypeOf.call(A.prototype, B.prototype)

참고 URL : https://stackoverflow.com/questions/14486110/how-to-check-if-a-javascript-class-inherits-another-without-creating-an-obj

반응형