Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 978
gekrish Avatar asked Aug 10 '10 13:08

gekrish


2 Answers

  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.

like image 166
Aaron Digulla Avatar answered Oct 04 '22 22:10

Aaron Digulla


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

like image 27
Rohit Avatar answered Oct 04 '22 20:10

Rohit