Function Invocation in JavaScript
? Function Invocation in JavaScript
What is Function Invocation?
Function invocation means calling or executing a function.
How a function is invoked affects the value of
thisinside it.
Types of Function Invocation
1. Regular Function Invocation
function foo() { console.log(this);}foo(); // In non-strict mode: global object (window in browsers) // In strict mode: undefinedthisrefers to the global object (windowin browsers) orundefinedin strict mode.
2. Method Invocation
const obj = { name: "Alice", greet() { console.log(this.name); }};obj.greet(); // "Alice"thisrefers to the object that owns the method (objhere).
3. Constructor Invocation
function Person(name) { this.name = name;}const p = new Person("Bob");console.log(p.name); // "Bob"Called with
new,thisrefers to the newly created object.Functions used as constructors typically start with a capital letter.
4. Indirect Invocation (call(), apply(), bind())
function greet() { console.log(this.name);}const user = { name: "Charlie" };greet.call(user); // "Charlie"greet.apply(user); // "Charlie"const boundGreet = greet.bind(user);boundGreet(); // "Charlie"callandapplyinvoke the function immediately with a specifiedthis.bindreturns a new function with boundthis.
Summary Table
| Invocation Type | How it's called | this value |
|---|---|---|
| Regular function | foo() | Global object or undefined |
| Method | obj.method() | obj |
| Constructor | new Func() | New object |
Indirect (call/apply) | func.call(obj), func.apply(obj) | obj |
| Bound function | boundFunc() | Bound this |
Want examples on how this behaves in arrow functions during invocation or common mistakes with invocation and this?