I am getting slightly confused about all this...
Chrome and Firefox both tell me different things, and I couldn't find any part in the spec that mentioned it, but:
in Chrome:
Object instanceof Function // true
Function instanceof Object // true
Worker instanceof Object // true
Worker instanceof Function // false <- WTF???
in FireFox:
Object instanceof Function // true
Function instanceof Object // true
Worker instanceof Object // false
Worker instanceof Function // false
of course, an initialised new Worker() is both a Worker and an Object, but why is the Worker constructor not a function?
Worker IS of type function. You can check that using the typeof
operator. However, it does not inherit the prototype of the Function constructor, hence it is not an instanceof
Function.
Here's a more practical example:
function fun(){};
Function.prototype.foo = 'my custom Function prototype property value';
console.log(fun.foo); //my custom Function prototype property value
console.log(fun instanceof Function); //true
console.log(typeof Worker); //function, the constructor
console.log(Worker.foo); //undefined, this host constructor does not inherit the Function prototype
console.log(Worker instanceof Function); //false
var worker = new Worker('test.js');
console.log(typeof worker); //object, the instance
console.log(worker.foo); //undefined, instance object does not inherit the Function prototype
console.log(worker instanceof Function); //false
From MDN:
The
instanceof
operator tests whether an object has in its prototype chain the prototype property of a constructor.
Worker does not inherit the Function constructor's prototype, hence it is not an instance of Function.
Here's an example using the typeof
operator to check if the user's browser supports the Web Workers API:
if (typeof window.Worker !== 'undefined') {
alert('Your browser supports Web Workers!');
} else {
alert('Sorry, but no.'); //too lazy to write a proper message for IE users
}
Fiddle
Worker
is a host object, not part of the language spec. It doesn't need to meet all the requirements of the language. There's nothing to say that it must represent itself as having been created from the Function
or any other constructor.
The others like Object
and Function
do because the language spec requires it of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With