什么是函数的数据类型:函数或对象?在JavaScript中 [英] What is Function's Data Type : function or object? in JavaScript

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

问题描述

MDN说:

六种原始数据类型:

  • 布尔
  • 未定义
  • 号码
  • 字符串
  • 符号(ECMAScript 6中的新功能)

  • Boolean
  • Null
  • Undefined
  • Number
  • String
  • Symbol (new in ECMAScript 6)

和对象

但是我混淆了函数数据类型和对象数据类型.

But I confused, the function data type and object data type.

让我们看看:

var func = function() { 
    console.log ('Hello World ! ')
};

var obj = { 
    property : something
}  


console.log(typeof(func)); // ===> function
console.log(typeof(obj)); // ===> object 

功能数据类型和对象数据类型是否不同?为什么 typeof(func)是函数?不是对象吗?该文档表示有7种数据类型(6种基本类型,1种对象).功能不包含在任何地方.

Is it different function data type and object data type? Why typeof(func) is function? not a object? The document said there are 7 data type (6 primitive, 1 object). function is not include anywhere.

直到现在,一年多以前,我认为函数的数据类型是对象,我听说函数是JavaScript中的一流对象,所以我对函数是对象没有疑问,但是今天我想了更多的时间,并想知道.

Until now, over 1 year, I think function's data type is object, I heard the function is first class object in JavaScript, so I don't have doubt about function is object but today I think more time, and wondered.

有什么不同吗?

推荐答案

您可以在逻辑上将 Function 视为 Object 的子类.它具有 Object 的所有方法以及一些特定于函数的方法(例如 .bind() .call() .apply()等...).

You can logically think of Function as a subclass of Object. It has all the methods of Object plus some more that are specific to a function (such as .bind(), .call(), .apply(), etc...).

为什么Javascript决定让 Function 报告它自己的唯一类型,但不是 Array (这是 Object 的类似派生)却是任何人的猜测,可能只有该语言的原始设计师才知道. Function 报告自己的类型非常有用,因此您可以轻松检查属性是否可以作为函数调用,这也许就是这样做的主要原因.

Why Javascript decided to make Function report it's own unique type, but not Array (which is a similar derivation from Object) is anyone's guess and probably only known to the original designers of the language. It is extremely useful that Function does report its own type so you can easily check if a property is callable as a function and perhaps that is the main reason why it was done this way.

这里演示了 Function 对象如何具有 Object 中的方法:

Here's a demonstration of how a Function object has the methods from an Object:

function f() {}
f.someProperty = "foo";

log(f.hasOwnProperty("someProperty"));
log(f instanceof Object);
log(f instanceof Function);

function log(x) {
    var div = document.createElement("div");
    div.innerHTML = x;
    document.body.appendChild(div);
}

这篇关于什么是函数的数据类型:函数或对象?在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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