在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs instanceof
在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs instanceof
当前回答
准确地说 应该在通过构造函数(通常是自定义类型)创建值的地方使用Instanceof。
var d = new String("abc")
而typeof用于检查仅由赋值创建的值,例如
var d = "abc"
其他回答
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/
当检查一个函数时,必须总是使用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来检查函数。
我建议使用原型的callback.isFunction()。
他们已经找出了其中的区别,你可以相信他们的理由。
我猜其他JS框架也有这样的东西。
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 对于典型的硬件,如果您创建一个具有1000万次迭代循环的脚本 指令:typeof STR == 'string'将花费9毫秒 而'string' instanceof string将花费19毫秒