15

a instanceof b完全等同a.constructor === b于? 如果不是,这两者有什么区别?

4

2 回答 2

21

不。

instanceof还检查“继承的”构造函数。

有关更多信息,请参阅规范。(这里这里

于 2013-08-11T14:22:10.913 回答
13

SLaks' answer is correct, but I would like to add that .constructor works on primitive types and instanceof doesn't:

"Hello World".constructor == String;    //true
"Hello World" instanceof String;    //false

The reason why the second condition is false is because "Hello World" is a primitive string and not an object so it isn't an instance of anything. In the first condition, on the other hand, when applying a method (such as constructor) to a primitive type, it gets converted to an object. So first "Hello World" gets converted to new String("Hello World") and then returns new String("Hello World").constructor which is String. This works the same way for numbers and booleans.

You can also use typeof on primitive types, but that won't work on objects:

typeof "Hello World";    //"string"
typeof new String("Hello World");    //"object"

So if you're dealing with strings, numbers or booleans and you don't need to worry about inheritance, you should use:

  • .constructor if you want to check if the variable is a string, number or boolean and it doesn't matter if it's a primitive type or an object.

    There are also other ways of doing this like typeof foo.valueOf() or (foo instanceof String || typeof foo == "string"), but .constructor is the shortest. However, the longer ways can be useful if for some reason you have classes that inherit String, Number or Boolean and you also want to check for inherited types.

  • instanceof if you want to check if the variable is a String, Number or Boolean object and not a primitive type.
  • typeof if you want to check if the type of the variable is a primitive type and not an object.
于 2019-02-20T11:19:12.567 回答