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?
An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.
function is a StreamBase data type and a reserved keyword. Use a constructor for the function data type to create a custom expression language function whose components are built-in functions, math operators, and even other functions.
In Javascript, there are five basic, or primitive, types of data. The five most basic types of data are strings, numbers, booleans, undefined, and null. We refer to these as primitive data types. A single variable can only store a single type of data.
A function object, or functor, is any type that implements operator(). This operator is referred to as the call operator or sometimes the application operator. The C++ Standard Library uses function objects primarily as sorting criteria for containers and in algorithms.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With