gpt4 book ai didi

javascript - 为什么函数是 javascript 中的对象?

转载 作者:行者123 更新时间:2023-11-30 17:03:00 24 4
gpt4 key购买 nike

请向我解释为什么函数是 javascript 中的对象?对象是具有属性的结构。属性的值可能是一个函数,我们称这个属性为方法。但是我们不能执行一个对象。我们不能这样做:

var cat = {name: 'Murzik', age: 17};
cat();

但是我们可以执行函数

var func = function() {
alert('Hello world!');
};
func();

那么,如果函数是对象,为什么我们可以这样做呢?请帮助我理解!谢谢!

最佳答案

因为 ECMAScript 规范是这样说的:

4.3.24 function

member of the Object type that is an instance of the standard built-in Function constructor and that may be invoked as a subroutine

注意

  • 有些对象是不可调用的:

    var obj = {};
    typeof obj; // "object" --> It's not callable
    obj(); // TypeError: obj is not a function
  • 一些对象是可调用的但不是函数:

    var obj = document.createElement('object');
    typeof obj; // "function" --> It's callable
    obj instanceof Function; // false --> It's not a function
  • 一些对象是可调用的并且是函数:

    function obj(){}
    typeof obj; // "function" --> It's callable
    obj instanceof Function; // true --> It's a Function instance
  • 并非所有的Function 实例都是可调用的:

    var obj = Object.create(Function.prototype);
    obj instanceof Function; // true --> It's a Function instance
    typeof obj; // "object" --> It's not callable
    obj(); // TypeError: obj is not a function

关于javascript - 为什么函数是 javascript 中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28528679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com