a instanceof b
完全等同a.constructor === b
于? 如果不是,这两者有什么区别?
2 回答
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 inheritString
,Number
orBoolean
and you also want to check for inherited types.instanceof
if you want to check if the variable is aString
,Number
orBoolean
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.