HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Function Invocation

In JavaScript, "invoking" a function simply means running the code inside it. While most functions are called using the () operator, the context in which they are called determines the value of the this keyword.


1. Invoking as a Function

This is the standard way to call a function. In a browser environment, the global object is the owner of the function. Therefore, this refers to the window object (unless in strict mode).

function myFunction(a, b) {
  return a * b;
}
myFunction(10, 2); // Result: 20

2. Invoking as a Method

In JavaScript, you can define functions as object methods. When a function is called as a method, this refers to the object that the method belongs to.

const myObject = {
  firstName: "Mim",
  lastName: "Akter",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}
myObject.fullName(); // Result: "Mim Akter"

3. Invoking with a Constructor

If a function invocation is preceded by the new keyword, it is a constructor invocation. It looks like it creates a new function, but since JavaScript functions are objects, you are actually creating a new object.

function Person(first, last) {
  this.firstName = first;
  this.lastName = last;
}

const myFriend = new Person("Redo", "Hub");
// "this" refers to myFriend
Summary of 'this':
  • Regular Function: refers to the Global Object.
  • Object Method: refers to the Object itself.
  • Constructor: refers to the Newly Created object.

The danger of 'this'

In a global function, this can be dangerous as it can accidentally modify global variables. In strict mode ("use strict";), this will be undefined if the function is called as a regular function.


Key Points to Remember

  • Invocation is the technical term for calling a function
  • The context determines the value of this
  • In a browser, the default global object is window
  • Strict mode makes this undefined in regular functions to increase safety
  • Functions called as methods always reference their parent object
  • Using new creates a unique instance of an object