JavaScript: Functions in the Object Model
In my previous posts, we have learned about the JavaScript Object Model using prototypes. We have created our own classes and seen how inheritance works. We have also understood the behavior of functions as objects in JavaScript.
In this post, we will see where JavaScript functions fit into the JavaScript Object Model.
Creating our function
Let us create a random function for our purposes.
const f1=function(){console.log("Hello World");} f1();
Our browser output is:
Examining our function
Now let us examine our function f1. Type in the following code:
console.log(f1);
Our browser output is:
Our function has some predefined attributes already. For our purposes, we are interested in the ‘prototype’ and <prototype> properties.
Log the prototype of function f1 to the console.
console.log(f1.prototype);
The output is:
Let us examine this.
As Javascript functions are also objects, they have a prototype. The ‘constructor’ property of the prototype points back to the main function itself.
If we examine the ‘<prototype>’ property of f1.prototype, we see that it is the same as Object.prototype, i.e., f1.prototype inherits from Object.prototype. This is exactly similar to the relationship between constructor functions have with the JavaScript Object.
The Function.prototype
Let us now examine the ‘<prototype>’ property of our function f1, i.e., the prototype object f1 inherits from.
Execute the following code:
console.log(Object.getPrototypeOf(f1));
The ‘Object.getPrototypeOf’ function takes in an object as an argument and returns the prototype that the object inherits from. In this case, we get the ‘<prototype>’ property of function ‘f1’.
Our browser output will show:
Leave a Reply