Ways to Invoke Functions in JavaScript
In JavaScript, functions can indeed be invoked in three ways: as a function, as a method, and as a constructor.
1. Function Invocation:
This is the simplest and most common way to call a function. Here, the function is defined and then invoked by its name.
Example:
|
|
2. Method Invocation:
A method is a function that’s been assigned as a property of an object. When a function is invoked as a method, the keyword this
inside the function body refers to the object of which the method is a property.
Example:
|
|
In the method invocation example, this
refers to obj
.
3. Constructor Invocation:
In JavaScript, a constructor is a function that initializes an object. When a function is invoked with the new
keyword, it’s being used as a constructor. Inside the function, this
refers to the new object being created.
Example:
|
|
In this constructor invocation example, this
refers to the new object (alice
) being created.
In summary, the way a function is invoked in JavaScript can greatly affect its behavior, especially with regard to the this
keyword. The flexibility of function invocation in JavaScript is a powerful feature, but it can also lead to confusion if you’re not aware of the distinctions.