Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of object is 'Worker' in JavaScript

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?

like image 901
phenomnomnominal Avatar asked Oct 22 '12 04:10

phenomnomnominal


2 Answers

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

like image 83
Fabrício Matté Avatar answered Sep 27 '22 19:09

Fabrício Matté


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.

like image 45
I Hate Lazy Avatar answered Sep 27 '22 19:09

I Hate Lazy