在JavaScript中:如果Object是一个函数,那么如果一个函数是一个对象的实例,它怎么可能呢

In JavaScript: If Object is a function then how can it be if a function is an instance of an object

本文关键字:一个 函数 如果 实例 怎么可能 一个对象 Object JavaScript      更新时间:2023-09-26

换句话说,第一个是什么?鸡蛋还是母鸡?我不明白JavaScript是如何实现的,因为我读到了以下内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function#Properties_and_Methods_of_Function。

正如您在控制台中看到的:

>Object instanceof Function
true
>new Function() instanceof Object
true

看起来像是一个致命的循环。

为什么所有这些:

typeof new Object()
typeof new Array()
typeof new Date()
typeof new RegExp()
typeof new Number()
typeof new Boolean()
typeof new String()

返回"object",但是这个:

typeof new Function()

返回"函数"

看起来。。。对象是从函数派生的吗?我不这么认为,因为:

>new Function() instanceof Object
true
>new Object() instanceof Function
false

所以不是。。。

看起来您混淆了类型、函数和对象。

简短回答:

在Javascript中,函数是对象。对象不是函数,而是存在创建和/或返回对象的函数。

带示例的详细答案:

你认为函数是对象是正确的。Object是一个函数,Function也是,如下控制台输出所示。

但当你说Object是一个函数时,你实际上是在谈论Object()函数,而不是类型object

// Object is a function
> Object
function Object() { [native code] }
// Function is a function
> Function
function Function() { [native code] }
// The type of Object is function
> typeof(Object)
"function"
// The type of the result of invoking the Object() function (AKA constructor, since using "new" keyword) is a new object
> typeof(new Object())
"object"
> new Object() instanceof Object
true
> new Function() instanceof Function
true
// note the difference
> new Object() instanceof Function
false
> new Function() instanceof Object
true

在您的示例中,在某些情况下,您实际上是在调用函数并查看函数的结果,而不是函数本身。例如,typeof(String) === "function",但typeof(new String()) === "object"(在本例中为"字符串"对象)。

当您使用new关键字调用这些函数时,您会得到一个新对象,其类是您调用的函数的名称。new Function() instanceof Object === true的原因是Object是以这种方式构造的任何对象的基类。Object是基类的名称,实例的类型是"object"(也就是说,根据类创建的对象,就像cookie切割器中的cookie一样)。