Skip to content Skip to sidebar Skip to footer

In Javascript, If Function Is Object Data Type (derived), Then How It Is Used As Object Constructor?

My understanding is, In javascript functions are objects. With that understanding I have written code for years. Suddenly this question comes to mind typeof Object is function, but

Solution 1:

The Object constructor function is provided by the underlying JS engine and is not created as part of the JavaScript program.

Solution 2:

Both Object and Function are constructor functions. Like all functions they are typeof 'function'. Because of the prototype hierarchy, they are also both instances of both Function and Object:

console.log(ObjectinstanceofObject)   // trueconsole.log(ObjectinstanceofFunction) // trueconsole.log(FunctioninstanceofObject)   // trueconsole.log(FunctioninstanceofFunction) // true

This is because functions are prototype-linked to the Object prototype.

Now when you callObject(), it creates an object, not a function:

let o = Object()
console.log(typeof o)              // objectconsole.log(o instanceofObject)   // trueconsole.log(o instanceofFunction) // falselet f = Function()
console.log(typeof f)              // funciónconsole.log(f instanceofObject)   // trueconsole.log(f instanceofFunction) // true because of prototype linking

So there's no circular reference, just some confusing names. Objects are not instances of functions, but there is a function called Object() that you can call to produce object instances. The hierarchy is Object -> Function. Functions inherit from Objects but both Object and Function are constructor functions that produce instances of their corresponding types.

Solution 3:

We create an object with a (constructor) function (which is an object). So which one comes first? object or function? chicken or egg? Seems like a circular reference?

We can create objects with constructors, yes, but that's not the only way. Consider object literals. We can create functions with the Function constructor function object, yes, but that's not the only way. Functions are usually created using function definitions.

So no, you neither need objects to create functions, nor do you need functions to create objects. In a typical JS program, they come in the order they are defined/evaluated in.

However you may ask about Object and Function. Yes, they have circular references set up between them and their prototype objects, but that's not a chicken-or-egg problem either. You can create circular references by trivial assignments. They don't really depend on each other, it's not like one was used to create the other. They came into existence separately. Which came first? We don't know, they are both builtin objects created by the environment. We don't care, they both already exist when our code runs.

Post a Comment for "In Javascript, If Function Is Object Data Type (derived), Then How It Is Used As Object Constructor?"