为什么在 JavaScript 类 A 中的 instanceof 函数,而 typeof 类 A 不是对象? [英] Why in JavaScript class A instanceof Function, but typeof class A is not an object?
问题描述
当我们说instance of"时,我们假设我们正在处理一个对象.为什么 JavaScript 的操作符 instanceof
在我们询问 (class A { }) instanceof Function
时返回 true
,而 typeof (class A { })==函数"
?为什么不是object
?
When we say "instance of", we assume that we are dealing with an object. Why JavaScript's operator instanceof
returns true
when we ask (class A { }) instanceof Function
, but typeof (class A { }) == "function"
? Why not object
?
推荐答案
当我们询问
(class A { }) instanceof Function
class
es 只是构造函数的语法糖.IE.class A {}
的求值产生一个函数.
class
es are just syntactic sugar for constructor functions. I.e. the evaluation of class A {}
produces a function.
以下两个示例是(或多或少)等价的,即它们产生相同的结果/值:
The following two examples are (more or less) equivalent, i.e. they produce the same result/value:
// class
class A {
constructor() {
this.foo = 42;
}
bar() {
console.log(this.foo);
}
}
// constructor function
function A() {
this.foo = 42;
}
A.prototype.bar = function() {
console.log(this.foo);
}
所有非原始值(字符串、数字、布尔值、空值、未定义、符号)在 JavaScript 中都是对象.函数也是对象,具有特殊的内部属性,使它们可调用(和/或可构造).
Everything that is not a primitive value (string, number, boolean, null, undefined, symbol) is an object in JavaScript. Functions are objects too, with special internal properties that makes them callable (and/or constructable).
为什么不反对?
typeof
返回字符串 "function"
作为函数值,因为它是在规范中定义的.
typeof
returns the string "function"
for function values because that's how it is defined in the specification.
这篇关于为什么在 JavaScript 类 A 中的 instanceof 函数,而 typeof 类 A 不是对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!