First of all, you cannot apply instanceof
to primitive values, that's why
"foo" instanceof String
returns false
. Primitives are not objects and hence cannot be an instance of a constructor function. *
So why does it seem to work inside the is_a
method?
In non-strict mode, the value of this
inside a function is always going to be an object (step 3). If this
value is not an object, it is implicitly converted to one. You can test this with console.log(typeof this)
.
That means that the string primitive "foo"
is converted to an String object new String("foo")
and that's why you can use instanceof
on it.
In strict mode, the value of this
doesn't have to be an object and is not automatically converted (step 1). Your method would fail in that case:
> Object.prototype.is_a = function (x) {
'use strict';
return this instanceof x;
}
> "foo".is_a(String)
false
*: That's a very simplified explanation. In reality, the instanceof
operator delegates the evaluation to the constructor function's internal [[HasInstance]]
method, which is defined to return false
if the passed value is not an object.