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.
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
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"
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
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.
thiswindowthis undefined in regular functions to
increase safetynew creates a unique instance of an object