为什么函数是javascript中的对象? [英] Why functions are objects in javascript?

查看:90
本文介绍了为什么函数是javascript中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但我们可以执行函数

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

所以,如果函数是对象,为什么我们可以做到这一点?
请帮我理解!
谢谢!

解决方案

因为ECMAScript规范是这样说的:


4.3 .24函数



是标准内置
Function 构造函数,可以作为子例程调用


请注意,


  • 有些对象不可调用:

      var obj = {}; 
    typeof obj; //object - >它不可调用
    obj(); // TypeError:obj不是函数


  • 有些对象可以调用,但不是函数:

      var obj = document.createElement('object'); 
    typeof obj; //功能 - >它可以调用
    obj instanceof Function; // false - >它不是一个函数


  • 一些对象是可调用的并且是函数:

      function obj(){} 
    typeof obj; //功能 - >它可以调用
    obj instanceof Function; // true - >它是一个函数实例


  • 并非所有函数实例可以被调用:

      var obj = Object.create(Function.prototype); 
    obj instanceof Function; // true - >它是一个函数实例
    typeof obj; //object - >它不可调用
    obj(); // TypeError:obj不是函数



Please, explain to me why functions are objects in javascript? An object is a structure with properties. Value of property may be a function and we call this property - method. But we can NOT execute an object. We can NOT do this:

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

But we can execute the function

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

So, if functions are objects why we can do this? Please, help me to understand! Thank's!

解决方案

Because the ECMAScript spec says so:

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

Note that

  • Some objects are not callable:

    var obj = {};
    typeof obj; // "object" --> It's not callable
    obj(); // TypeError: obj is not a function
    

  • Some objects are callable but are not functions:

    var obj = document.createElement('object');
    typeof obj; // "function" --> It's callable
    obj instanceof Function; // false --> It's not a function
    

  • Some objects are callable and are functions:

    function obj(){}
    typeof obj; // "function" --> It's callable
    obj instanceof Function; // true --> It's a Function instance
    

  • Not all Function instances are callable:

    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中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆