β 1. What Is Function Invocation?
Function invocation means executing a function β making it run.
jsCopyEditfunction greet() {
console.log("Hello!");
}
greet(); // π Function is invoked here
π 2. Types of Function Invocation
JavaScript provides several ways to invoke functions, each with different this
behavior.
A. Simple Invocation
Most common: call a function by its name followed by parentheses ()
.
jsCopyEditfunction add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
B. Method Invocation (Object Context)
When a function is a method of an object, this
refers to the object.
jsCopyEditconst user = {
name: "Alice",
greet: function() {
console.log("Hi, I'm " + this.name);
}
};
user.greet(); // Hi, I'm Alice
C. Constructor Invocation (new
)
When using the new
keyword, this
refers to a new object being created.
jsCopyEditfunction Person(name) {
this.name = name;
}
const p = new Person("Tom");
console.log(p.name); // Tom
D. Indirect Invocation: call()
and apply()
Allows you to set this
manually.
jsCopyEditfunction sayName() {
console.log(this.name);
}
const person = { name: "Dave" };
sayName.call(person); // Dave
sayName.apply(person); // Dave
call()
passes arguments one by one,apply()
takes them in an array.
E. Arrow Function Invocation
Arrow functions donβt have their own this
β they inherit it from the enclosing context.
jsCopyEditconst person = {
name: "Emma",
greet: () => {
console.log("Hi, I'm " + this.name);
}
};
person.greet(); // β οΈ "Hi, I'm undefined"
π 3. IIFE (Immediately Invoked Function Expression)
Runs immediately after being defined.
jsCopyEdit(function() {
console.log("I run automatically!");
})();
Arrow function version:
jsCopyEdit(() => {
console.log("Arrow IIFE");
})();
π 4. Event-Driven Invocation
Functions can be invoked in response to events (e.g. clicks):
jsCopyEditdocument.getElementById("btn").onclick = function() {
alert("Button clicked!");
};
π 5. Timer-Based Invocation
Invoke a function after a delay or repeatedly.
jsCopyEditsetTimeout(function() {
console.log("Runs after 2 seconds");
}, 2000);
setInterval(() => {
console.log("Repeats every 3 seconds");
}, 3000);
π§ͺ Practice Challenges
- Define and invoke a function
welcome()
that prints “Welcome!”. - Create an object with a method that says
"My name is <name>"
. - Use
call()
to invoke a function with a customthis
.
π§ Summary Table
Invocation Type | Example | this Value |
---|---|---|
Simple | myFunc() | undefined or window in non-strict |
Method | obj.method() | obj |
Constructor | new MyFunc() | new object |
call() / apply() | func.call(obj) | manually set to obj |
IIFE | (function() {})() | window (non-strict) |
Arrow Function | (() => {})() | inherited from lexical scope |
Would you like:
- π A PDF version of this tutorial?
- π» An interactive JSFiddle or CodePen?
- π§ A mini quiz on invocation types?