Reputation: 7628
The MDN said :
Six data types that are primitives:
Symbol (new in ECMAScript 6)
and Object
But I confused, the function data type and object data type.
Let's see :
var func = function() {
console.log ('Hello World ! ')
};
var obj = {
property : something
}
console.log(typeof(func)); // ===> function
console.log(typeof(obj)); // ===> object
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.
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.
Is it different?
Upvotes: 25
Views: 11350
Reputation: 10372
typeof
returns the type of what ever is passed to it. A function is an object ((function () {}) instanceof Object === true
), but the typeof
function is defined to return "function"
when an Object implements [[Call]] in ECMA-262 is supplied to it.
Functions are objects, but typeof
treats them as a special case.
Upvotes: 4
Reputation: 707456
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...).
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.
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);
}
Upvotes: 18