在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs instanceof
在我的特殊情况下:
callback instanceof Function
or
typeof callback == "function"
这有关系吗,有什么区别?
额外的资源:
花园typeof vs instanceof
当前回答
instanceof将不适用于原语,例如"foo" instanceof String将返回false,而typeof "foo" == " String "将返回true。
另一方面,当涉及到自定义对象(或类,无论你想叫它们什么)时,typeof可能不会做你想做的事情。例如:
function Dog() {}
var obj = new Dog;
typeof obj == 'Dog' // false, typeof obj is actually "object"
obj instanceof Dog // true, what we want in this case
函数碰巧既是“函数”原语,又是“函数”的实例,这有点奇怪,因为它不像其他原语类型那样工作,例如。
(typeof function(){} == 'function') == (function(){} instanceof Function)
but
(typeof 'foo' == 'string') != ('foo' instanceof String)
其他回答
使用instanceof,因为如果你改变了类的名字,你会得到一个编译器错误。
准确地说 应该在通过构造函数(通常是自定义类型)创建值的地方使用Instanceof。
var d = new String("abc")
而typeof用于检查仅由赋值创建的值,例如
var d = "abc"
我从小接受严格的面向对象教育
callback instanceof Function
字符串容易出现我糟糕的拼写或其他拼写错误。而且我觉得读起来更好。
当然这很重要........!
让我们用例子来解释一下。在我们的例子中,我们将以两种不同的方式声明函数。
我们将同时使用函数声明和函数构造函数。我们将了解typeof和instanceof在这两种不同场景中的行为。
使用函数声明创建函数:
function MyFunc(){ }
typeof Myfunc == 'function' // true
MyFunc instanceof Function // false
对于这种不同的结果,可能的解释是,因为我们做了一个函数声明,typeof可以理解它是一个函数。因为typeof检查typeof的表达式是否被操作,在我们的例子中,MyFunc是否实现了Call Method。如果它实现了Call方法,它就是一个函数。为了澄清,请检查ecmascript的typeof规范。
使用函数构造函数创建函数:
var MyFunc2 = new Function('a','b','return a+b') // A function constructor is used
typeof MyFunc2 == 'function' // true
MyFunc2 instanceof Function // true
这里typeof断言MyFunc2是一个函数,也是一个instanceof操作符。我们已经知道typeof检查MyFunc2是否实现了Call方法。由于MyFunc2是一个函数,它实现了调用方法,这就是typeof如何知道它是一个函数。另一方面,我们使用函数构造函数来创建MyFunc2,它成为函数构造函数的一个实例。这就是为什么instanceof也解析为true。
用什么更安全?
我们可以看到,在这两种情况下,typeof操作符都可以成功地断言我们在处理一个函数,它比instanceof更安全。instanceof在函数声明的情况下将失败,因为函数声明不是function构造函数的实例。
最佳实践:
正如Gary Rafferty所建议的,最好的方法应该同时使用typeof和instanceof。
function isFunction(functionItem) {
return typeof(functionItem) == 'function' || functionItem instanceof Function;
}
isFunction(MyFunc) // invoke it by passing our test function as parameter
没有必要用上面的大量例子来压倒你,只需要记住两个观点:
typeof var; is an unary operator will return the original type or root type of var. so that it will return primitive types(string, number, bigint, boolean, undefined, and symbol) or object type. in case of higher-level object, like built-in objects (String, Number, Boolean, Array..) or complex or custom objects, all of them is object root type, but instance type built base on them is vary(like OOP class inheritance concept), here a instanceof A - a binary operator - will help you, it will go through the prototype chain to check whether constructor of the right operand(A) appears or not.
所以当你想检查“根类型”或使用基元变量时,使用“typeof”,否则使用“instanceof”。
Null是一种特殊情况,它看起来很原始,但实际上是object的特殊情况。使用a === null代替检查null。
另一方面,function也是一种特殊情况,它是内置对象,但typeof返回函数
正如你所看到的,instanceof必须遍历原型链,而typeof只检查根类型一次,所以很容易理解为什么typeof比instanceof快