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:
Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript. That means
function
inherits fromobject
.Object instances can contain more instances which can be functions. That's what we call a "method" (since it has an automatic
this
variable).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
- Primitive types - numbers, strings, booleans, null and undefined.
- 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.
-
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. -
Most of the non-primitive type has
prototype
property where all inherited stuff lives. Math doesn't have prototype. -
All objects inherit from
Object.prototype
which inherits fromnull
.object <- Object.prototype <- null
-
All native functions inherit from Function.prototype which inherits from Object.prototype.
function <- Function.prototype <- Object.prototype <- null
-
Arrays inherit from
Array.prototype
which inherits fromObject.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