Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Function Invocation in JavaScript

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 this inside 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: undefined
  • this refers to the global object (window in browsers) or undefined in strict mode.


2. Method Invocation

const obj = {  name: "Alice",  greet() {    console.log(this.name);  }};obj.greet();  // "Alice"
  • this refers to the object that owns the method (obj here).


3. Constructor Invocation

function Person(name) {  this.name = name;}const p = new Person("Bob");console.log(p.name);  // "Bob"
  • Called with new, this refers 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"
  • call and apply invoke the function immediately with a specified this.

  • bind returns a new function with bound this.


Summary Table

Invocation TypeHow it's calledthis value
Regular functionfoo()Global object or undefined
Methodobj.method()obj
Constructornew Func()New object
Indirect (call/apply)func.call(obj), func.apply(obj)obj
Bound functionboundFunc()Bound this

Want examples on how this behaves in arrow functions during invocation or common mistakes with invocation and this?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql