2013-01-07 4 views
4

JavaScript 객체의 프로토 타입을 결정하는 가장 좋은 방법은 무엇입니까? 나는 다음 두 가지 방법을 알고 있지만 브라우저 간 지원 측면에서 어떤 것이 "가장 좋은"방법인지 (또는 더 나은 방법이 있는지는 확실하지 않습니다.)JS 객체의 프로토 타입 결정

if (obj.__proto__ === MY_NAMESPACE.Util.SomeObject.prototype) { 
    // ... 
} 

또는

if (obj instanceof MY_NAMESPACE.Util.SomeObject) { 
    // ... 
} 
+1

다른 메소드가 약간 hackish로 보이고 ECMAScript의 다음 버전 작업을 쉽게 중단 할 수 있기 때문에 instanceof라고합니다. –

+1

많은 도움이되는 훌륭한 기사가 있습니다. [http://ejohn.org/blog/objectgetprototypeof/](http://ejohn.org/blog/objectgetprototypeof/) – Ramin

답변

6

instanceof가 선호된다. __proto__은 비표준이며, 특히 Internet Explorer에서는 작동하지 않습니다.

Object.getPrototypeOf(obj)__proto__과 동일한 기능을하는 ECMAScript 5 기능입니다.

instanceof은 전체 프로토 타입 체인을 검색하는 반면 getPrototypeOf은 한 단계 위를 찾습니다.

일부 사용시주의 사항 : __proto__이 (- it will most likely be standard in ECMAScript 6 아직)없는 동안

new String() instanceof String // true 

(new String()).__proto__ == String // false! 
            // the prototype of String is (new String("")) 
Object.getPrototypeOf(new String()) == String // FALSE, same as above 

(new String()).__proto__ == String.prototype   // true! (if supported) 
Object.getPrototypeOf(new String()) == String.prototype // true! (if supported) 
+0

정보 및 사례를 제공해 주셔서 감사합니다! :) –

3

instanceof는 표준입니다.

+0

링크를 가져 주셔서 감사합니다! –