3

i am using

var foo = function(){}

typeof(foo) - returns function instead of Object

while javascript concept tell that all function in javascript are objects?

Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77
Atul Kumar
  • 83
  • 1
  • 6
  • The fact that they are created as expression and that they can be assigned, compared (by reference) and that you can add arbitrary properties should suffice, no? – Lucero Jan 28 '17 at 09:29

5 Answers5

6

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
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

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
Tomzan
  • 2,808
  • 14
  • 25
1

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

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
1

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.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
0

console.log(Function.prototype instanceof Object);

Atul Kumar
  • 83
  • 1
  • 6