Every Object is a function and every function is Object - Which is Correct?

I was reading this link JavaScript_syntax

This seems to be cyclic - that every function is an Object and every Object itself is a function. Which is the atomic one? Can someone explain in a better way?


Solution 1:

  1. Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript. That means function inherits from object.

  2. Object instances can contain more instances which can be functions. That's what we call a "method" (since it has an automatic this variable).

  3. Since you can't "call" every Object instance, not every object is a function.

Solution 2:

I think this concept is often misunderstood.

A utility to visualize JS types relationship http://jstype.herokuapp.com/#/home

Javascript Data Types

  1. Primitive types - numbers, strings, booleans, null and undefined.
  2. All non-primitive types are object:

var foo = { }; 
var foo = [1, 2, 3]; 
var foo = function abc() { return "hello world"; }; 
var foo = new Number(30); 
var foo = new String("Hello World"); 
var foo = new Boolean(true); 
var foo = new RegExp(/[foo]+/);

// All 'foo` are object. 
  1. All primitive types have a corresponding Constructor Function wiz. Array, Number, String, Boolean, RegExp. As all functions are objects, they are objects too. So we can call them Constructor Function Objects.

  2. Most of the non-primitive type has prototype property where all inherited stuff lives. Math doesn't have prototype.

  3. All objects inherit from Object.prototype which inherits from null.
    object <- Object.prototype <- null

  4. All native functions inherit from Function.prototype which inherits from Object.prototype.
    function <- Function.prototype <- Object.prototype <- null

  5. Arrays inherit from Array.prototype which inherits from Object.prototype.
    array <- Array.prototype <- Object.prototype <- null

Must read MDN: Inheritance and prototype chain
To get confused Stackoverflow: prototype in JavaScript
Stack Overflow: Function prototype explained

Solution 3:

Every function is an object. Objects can contain functions (methods) but an object is not necessary a function.

Solution 4:

Also Function is always a property of an object.

This mean that all functions in JavaScript is always bound to an object. If you don't specify an object to bind a function to it's bound to the window object (Also called global functions)

..fredrik