i am using
var foo = function(){}
typeof(foo)
- returns function instead of Object
while javascript concept tell that all function in javascript are objects?
i am using
var foo = function(){}
typeof(foo)
- returns function instead of Object
while javascript concept tell that all function in javascript are objects?
First and foremost, there's the fact that the specification explicitly states they're objects, in a lot of places, including here where it defines the term "function":
function
member of the Object type that may be invoked as a subroutine
Empirically, there are lots of ways to prove it, but one of the simplest is to assign a value to a property on it:
var foo = function() { };
foo.myProperty = "my value";
console.log(foo.myProperty); // "my value"
Or use one as a prototype (which is unusual, but possible), which proves it as only objects can be prototypes:
var foo = function() { };
var obj = Object.create(foo);
console.log(Object.getPrototypeOf(obj) === foo); // true
How about this for a test
> x = function(){}
<- function (){}
> x.a = "Asd"
<- "Asd"
> x
<- function (){}
> x.a
<- "Asd"
Doing the same on an integer will result in undefined assignment
> x = 1
<- 1
> x.a = 123
<- 123
> x
<- 1
> x.a
<- undefined
See my list of proper ways to test if a value belongs to the Object type.
They detect functions as objects, e.g.
var func = function(){};
Object(func) === func; // true --> func is an object
If you want a more formal proof you will need to see the spec, for example in ECMAScript Overview
a function is a callable object
You can prove this very simply:
console.log(Object.getPrototypeOf(Function.prototype));
console.log(Object.prototype === Object.getPrototypeOf(Function.prototype));
// or, being evil
Object.prototype.testFn = () => console.log('Exists on all objects');
({}).testFn();
[].testFn();
(new Number(5)).testFn();
Math.sqrt.testFn();
The first two lines demonstrate that the next step in the prototype chain beyond Function.prototype
is Object.prototype
.
The other lines show that you can add a property to Object.prototype
(seriously don't do this ever) and it exists on all objects. In this case, we test it on an empty object, an empty array, a Number
object and on the Math.sqrt
function. By adding a property (a function in this case) to Object.prototype
, all the others gain the property too.