DEV Community

Athithya Sivasankarar
Athithya Sivasankarar

Posted on

Using Objects as Functions & Function Constructor in JavaScript

In JavaScript, functions are powerful.
They can behave like objects, and we can also create functions dynamically using constructors.

Functions are Objects in JavaScript

In JavaScript, functions are actually special types of objects.

This means:

  • We can store functions inside objects
  • We can call them like methods

Example: Object with Function

const user = {
name: "Athithya",
greet: function() {
return "Hello " + this.name;
}
};

console.log(user.greet());

Output:

Hello Athithya

Explanation

  • "user" → object
  • "greet" → function inside object
  • "this.name" → refers to object value

This is called a method

Functions Can Have Properties (Like Objects)

function greet() {}

greet.message = "Hello";

console.log(greet.message);

Output:

Hello

Explanation

Here:

  • "greet" is a function
  • But we added a property → like an object

So, functions behave like objects

Function Constructor

What is Function Constructor?

A Function Constructor is used to create a function dynamically using the "Function" keyword.

Example

const add = new Function("a", "b", "return a + b");

console.log(add(2, 3));

Output:

5

Explanation

  • ""a", "b"" → parameters
  • ""return a + b"" → function body
  • "new Function()" → creates function

Reference

Top comments (0)