JavaScript Function Invocation
In JavaScript, the code inside a function is executed when the function is invoked (called). There are several ways to invoke a function, and each affects the value of 'this' inside the function differently.
Calling a Function
The most common way to invoke a function is by calling it directly using parentheses. When a function is called as a standalone function (not a method), 'this' refers to the global object (window in browsers) or undefined in strict mode.
function greet(name) {
console.log(`Hello, ${name}!`);
return `Hello, ${name}!`;
}
// Invoke with parentheses
greet("Alice");
greet("Bob");
// Store result
let message = greet("Charlie");
console.log(message);Invoking as a Method
When a function is stored as a property of an object, it is called a method. When invoked as a method, 'this' refers to the object that owns the method.
let person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return `${this.firstName} ${this.lastName}`;
}
};
// Invoke as a method — 'this' is the person object
console.log(person.fullName());
let calculator = {
value: 0,
add: function(n) { this.value += n; return this; },
subtract: function(n) { this.value -= n; return this; },
result: function() { return this.value; }
};
// Method chaining
let total = calculator.add(10).add(5).subtract(3).result();
console.log(total);Constructor Invocation with new
When a function is invoked with the 'new' keyword, it acts as a constructor. A new empty object is created, 'this' is bound to the new object, and the object is returned automatically (unless the function returns a different object).
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
return `Hi, I'm ${this.name}, age ${this.age}`;
};
}
// Invoke with 'new' — creates a new object
let alice = new Person("Alice", 30);
let bob = new Person("Bob", 25);
console.log(alice.greet());
console.log(bob.greet());
console.log(alice instanceof Person);
console.log(typeof alice);Invoking with call() and apply()
The call() and apply() methods let you invoke a function with a specific 'this' value. call() takes arguments individually, while apply() takes them as an array. These are useful for borrowing methods from other objects.
function introduce(greeting, punctuation) {
console.log(`${greeting}, I'm ${this.name}${punctuation}`);
}
let person1 = { name: "Alice" };
let person2 = { name: "Bob" };
// call() — arguments passed individually
introduce.call(person1, "Hello", "!");
introduce.call(person2, "Hi", ".");
// apply() — arguments passed as array
introduce.apply(person1, ["Hey", "!!"]);
introduce.apply(person2, ["Greetings", "..."]);
// Borrowing methods
let numbers = [5, 2, 8, 1, 9];
let max = Math.max.apply(null, numbers);
console.log("Max:", max);Self-Invoking Functions (IIFE)
A self-invoking function (Immediately Invoked Function Expression, or IIFE) runs automatically when it is defined. It is wrapped in parentheses and followed by (). This pattern creates a private scope.
// Basic IIFE
(function() {
let message = "I run immediately!";
console.log(message);
})();
// IIFE with parameters
(function(name) {
console.log(`Hello, ${name}!`);
})("World");
// Arrow function IIFE
(() => {
console.log("Arrow IIFE!");
})();
// IIFE that returns a value
let counter = (function() {
let count = 0;
return {
increment: function() { return ++count; },
getCount: function() { return count; }
};
})();
console.log(counter.increment());
console.log(counter.increment());
console.log(counter.getCount());| Invocation Type | Syntax | this Value |
|---|---|---|
| Function call | myFunc() | Global object / undefined (strict) |
| Method call | obj.myFunc() | The object (obj) |
| Constructor | new MyFunc() | New empty object |
| call() | func.call(obj, args) | First argument (obj) |
| apply() | func.apply(obj, [args]) | First argument (obj) |
| IIFE | (function(){})(); | Global object / undefined (strict) |