JavaScript 中'Worker'的对象类型是什么



我对此感到有些困惑...

Chrome和Firefox都告诉我不同的事情,我找不到提到它的规格中的任何部分,但是:

在Chrome中:

Object instanceof Function // true
Function instanceof Object // true
Worker instanceof Object // true
Worker instanceof Function // false <- WTF???

在Firefox中:

Object instanceof Function // true
Function instanceof Object // true
Worker instanceof Object // false
Worker instanceof Function // false

当然,初始化的新工作者()既是工人又是对象,但是为什么工人构造函数不是函数?

worker 类型函数的。您可以使用typeof运算符检查。但是,它不继承函数构造函数的原型,因此它不是instanceof函数。

这是一个更实用的例子:

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​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

来自MDN:

instanceof操作员测试一个对象是否具有原型中的对象 将构造函数的原型特性链。

Worker不能继承函数构造函数的原型,因此它不是函数的实例。


这是使用typeof操作员检查用户浏览器是否支持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
}​

小提琴

Worker是主机对象,而不是语言规范的一部分。它不需要满足语言的所有要求。没有什么可说的是,它必须代表自己是从Function或任何其他构造函数创建的。

其他像ObjectFunction这样的人这样做,因为语言规格需要它们。

最新更新