var a=new Boolean(false);
var b=false;
alert(a instanceof Boolean);
alert(b instanceof Boolean);
The first true pops up
The second one pops up false
Why? I don’t quite understand.
阿神2017-07-05 10:58:40
There are two types of values in JavaScript: primitive types and reference types (objects).
false
is a boolean
primitive value, not an object, so false instanceof Boolean
is false
.
Similarly, "foo" instanceof String
is also false
.
Checking primitive types can be done with typeof
.
You will see that the value of typeof false
is "boolean"
, note the lowercase "b".
and:
typeof Boolean
is "function"
Boolean instanceof Object
is true
Since JavaScript performs type conversion silently, users often ignore the differences between types. For example, var length = "hello world".length
converts the original type string
into an instance of the String
object.
PHP中文网2017-07-05 10:58:40
var a = new Boolean(false);
var b = false;
alert(typeof a); // 'Object'
alert(typeof b); // 'Boolean'
alert(a === b); // false
过去多啦不再A梦2017-07-05 10:58:40
instanceof is used to determine whether an object is an instance of a certain constructor.
b is obviously not an object
女神的闺蜜爱上我2017-07-05 10:58:40
Except for object, all other types are basic types. What you are here is to determine whether it is a Boolean instance, which belongs to object. The subsequent basic type is false. If it is not a Boolean instance produced by new, the result will of course be false.