JavaScript has primitive data types and objects. Every function in JavaScript is in fact an object — it is an instance of the Function
constructor. You can see this with the following code:
// function declaration/statement (function foo(){}).constructor === Function; // true
// anonymous function (function(){}).constructor === Function; // true
// function expression const expr = function() {}; expr.constructor === Function; // true
// arrow function (() => {}).constructor === Function; // true
The context bounded to functions could be different depending on how you define a function.
The difference between a Function
object and other objects in JavaScript is the fact that functions can be invoked/called directly (without creating a new constructor instance):
function foo() { console.log('called'); } console.log(foo()); // 'called'
Like other objects, functions can have properties and methods, and they can be instantiated (when the constructor is called with the new
keyword):
function Foo(prop) { this.prop = prop; this.method = function() { console.log('foo'); } } const foo = new Foo('bar'); console.log(foo.prop); // 'bar' console.log(foo.method()); // 'foo'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.