DEV Community

Athithya Sivasankarar
Athithya Sivasankarar

Posted on

Using Objects as Functions, Function Constructor & this Keyword in JavaScript

JavaScript is a flexible language where functions and objects work closely together.

  • Functions as objects
  • Function constructor
  • thiskeyword

1. Functions as Objects

In JavaScript, functions are special types of objects.

This means:

  • Functions can be stored inside objects
  • Functions can have properties

Example: Function inside Object

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

console.log(user.greet());
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Athithya

Explanation

  • user → object
  • greet → function (method)
  • this.name → refers to object value

Functions Can Have Properties

function greet() {}

greet.msg = "Hello";

console.log(greet.msg);
Enter fullscreen mode Exit fullscreen mode

Output:

Hello

So, functions behave like objects.

2. Function Constructor

What is it?

A constructor function is used to create multiple objects using new.

Example

function Student(name, age) {
    this.name = name;
    this.age = age;

    this.display = function() {
        return this.name + " " + this.age;
    };
}

let s1 = new Student("Ram", 20);
console.log(s1.display());
Enter fullscreen mode Exit fullscreen mode

Output:

Ram 20

Explanation

  • Student → constructor function
  • this.name → assign value
  • new Student() → creates object

3. this Keyword

this refers to the current object.

Example

const user = {
    name: "Athithya",
    show: function() {
        console.log(this.name);
    }
};

user.show();
Enter fullscreen mode Exit fullscreen mode

Output:

Athithya

Explanation

  • this.name → refers to object's name
  • Inside object → this = that object

Reference

Top comments (0)