在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs instanceof
在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs instanceof
当前回答
instanceof在Javascript中是不可靠的——我相信主流框架都尽量避免使用它。不同的窗口是它可以打破的方式之一-我相信职业层次结构也可以混淆它。
有更好的方法来测试对象是否为某种内置类型(通常是您想要的类型)。创建实用函数并使用它们:
function isFunction(obj) {
return typeof(obj) == "function";
}
function isArray(obj) {
return typeof(obj) == "object"
&& typeof(obj.length) == "number"
&& isFunction(obj.push);
}
等等。
其他回答
其他重要的实际差异:
// Boolean
var str3 = true ;
alert(str3);
alert(str3 instanceof Boolean); // false: expect true
alert(typeof str3 == "boolean" ); // true
// Number
var str4 = 100 ;
alert(str4);
alert(str4 instanceof Number); // false: expect true
alert(typeof str4 == "number" ); // true
性能
在两者都适用的情况下,Typeof比instanceof更快。
根据您的引擎,有利于typeof的性能差异可能在20%左右。(您的里程可能有所不同)
下面是Array的基准测试:
var subject = new Array();
var iterations = 10000000;
var goBenchmark = function(callback, iterations) {
var start = Date.now();
for (i=0; i < iterations; i++) { var foo = callback(); }
var end = Date.now();
var seconds = parseFloat((end-start)/1000).toFixed(2);
console.log(callback.name+" took: "+ seconds +" seconds.");
return seconds;
}
// Testing instanceof
var iot = goBenchmark(function instanceofTest(){
(subject instanceof Array);
}, iterations);
// Testing typeof
var tot = goBenchmark(function typeofTest(){
(typeof subject == "object");
}, iterations);
var r = new Array(iot,tot).sort();
console.log("Performance ratio is: "+ parseFloat(r[1]/r[0]).toFixed(3));
结果
instanceofTest took: 9.98 seconds.
typeofTest took: 8.33 seconds.
Performance ratio is: 1.198
typeof:根据MDN文档,typeof是一个一元操作符,返回指示未求值操作数类型的字符串。
在字符串原语和字符串对象的情况下,typeof返回如下:
const a = "I'm a string primitive";
const b = new String("I'm a String Object");
typeof a; --> returns 'string'
typeof b; --> returns 'object'
Instanceof:是一个二进制操作符,接受一个对象和一个构造函数。它返回一个布尔值,指示对象的原型链中是否有给定的构造函数。
当应用于上面的string实例时,并与string进行比较,它的行为如下:
const a = "I'm a string primitive";
const b = new String("I'm a String Object");
a instanceof String; --> returns false
b instanceof String; --> returns true
参考:https://bambielli.com/til/2017-06-18-typeof-vs-instanceof/
根据MDN关于typeof的文档,用"new"关键字实例化的对象类型为'object':
typeof 'bla' === 'string';
// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
而关于instanceof点的文档说明:
const objectString = new String('String created with constructor');
objectString instanceOf String; // returns true
objectString instanceOf Object; // returns true
因此,如果有人想检查,例如,某东西是一个字符串,无论它是如何创建的,最安全的方法是使用instanceof。
当检查一个函数时,必须总是使用typeof。
区别在于:
var f = Object.create(Function);
console.log(f instanceof Function); //=> true
console.log(typeof f === 'function'); //=> false
f(); // throws TypeError: f is not a function
这就是为什么决不能使用instanceof来检查函数。