2016-10-01 5 views
3

this question에서 나는 생성자를 사용할 제안을 보지 못했습니다.JavaScript에서 type을 감지하기위한 생성자와 typeof 비교

그래서 그 대신 typeof callback == "function"

의 나는 callback && (callback.constructor==Function)를 사용합니다.

나에게 그것은 메모리 포인터와의 비교가 런타임 성능과 코딩 안전면에서 문자열 비교보다 항상 더 낫다는 것이 확실합니다.

모든 유형을 감지하고 못생긴 것을 잊어 버리는데 왜 생성자를 사용하지 않습니까? typeof?

그것은 모든 원시 형, 함수 및 배열에 대한 작동합니다

undefined === undefined 
null === null 
[1,2,3].constructor == Array 
(1).constructor == Number 
(true).constructor == Boolean 
(()=>null).constructor == Function 
'abc'.constructor == String 
(new Date()).constructor == Date 
else it's an object, where instanceof helps to detect it's parents if needed. 

string interning 경우는 다음 런타임 성능 이점이 사라질에 의존 할 수있다. 그러나 안전한 코딩 이점은 여전히 ​​유지됩니다.

+0

은'function'와'function' 비교? – Rayon

답변

2

instanceOf은 상속 된 생성자와 작동하기 때문에 더 좋습니다. .constructor은 객체의 변경 가능한 속성이므로 단순히 변경 만 할 수 있으므로 확인하는 것은 좋지 않습니다. instanceOf을 변경할 수 없습니다.

const x = new Date(); 
 
console.log("Date Constructor", x.constructor); 
 
x.constructor = "herpderpderp"; 
 
console.log("Date Constructor", x.constructor);

+0

객체가 다른 생성자로 생성 된 후에 생성자를 할당하는 것은 잘못된 코딩 방법입니까? 그러한 과제의 실질적인 이익은 무엇입니까? 실제로 사용 되는가? – alpav

+0

다른 써드 파티 스크립트를 잠재적으로 엉망으로 만들 수있는 생성자를 오버라이드하고 있기 때문에 나는 그렇게 생각한다. 나는 그것을 조작 할 때 아무런 유익도 볼 수 없으며, 솔직히 발전하기 위해 5 년 동안 그것을 사용한 적이 없습니다. –

+0

그렇다면 실질적으로 생성자가 변경 가능하다는 것은 중요하지 않습니다. 이는 typeof vs 생성자를 사용하는 유일한 장점입니다. 이 경우 귀하의 대답은 내 질문에 답하지 않습니다 - "왜 constructor 대신 typeof를 사용합니까?". – alpav

1

또한 또한 getPrototypeOf 및 isPrototypeOf을 사용하여 프리미티브 작업을 모두 테스트를 위해 자신의 함수를 정의 할 수 있습니다. 예컨대 :

function typeOf(obj) { 
    return Object.getPrototypeOf(obj).constructor; 
} 

typeOf(2) === Number // true 
typeOf("cats") === String // true 
class Foo {} 
typeOf(new Foo()) === Foo // true 

class Bar extends Foo {} 
typeOf(new Bar()) === Bar // true 
typeOf(new Bar()) === Foo // false  

var b = new Number(3) 
if (typeOf(b) === Number) { 
    console.log(b.valueOf() + 5) 
} 

function instanceOf(obj, type) { 
    var objType = typeOf(obj) 
    return (
     // Allow native instanceof in case of Symbol.hasInstance 
     obj instanceof type || 
     // Handle case where is of type type 
     typeOf(obj) === type || 
     // Handle general case 
     type.isPrototypeOf(objType) || 
     // Handle special case where type.prototype acts as a 
     // prototype of the object but its type isn't in the 
     // prototype chain of the obj's type 
     // OPTIONALLY remove this case if you don't want 
     // primitives to be considered instances of Object 
     type.prototype.isPrototypeOf(objType.prototype) 

    ); 
} 

instanceOf(3, Number) // true 
instanceOf(new Number("2"), Number) // true 
instanceOf(2, Number) // true, OPTIONAL with the last condition 
         // but is probably preferable as 2 does 
         // indeed get all methods of Objects 
class Hat {} 
instanceOf(new Hat(), Hat) // true 
class Fedora extends Hat {} 
instanceOf(new Fedora(), Fedora) // true 
instanceOf(new Fedora(), Hat) // true 
instanceOf(new Fedora(), Object) // true