Eslam Ahmed
Eslam

Follow

Eslam

Follow
The 5 Ways you can invoke a function in Javascript in 1 minute

Photo by Pavan Trikutam on Unsplash

The 5 Ways you can invoke a function in Javascript in 1 minute

Eslam Ahmed's photo
Eslam Ahmed
·Dec 8, 2021·

2 min read

Table of contents

  • Function Excution Types in JavaScript

Function Excution Types in JavaScript

1- Normal function declaration and calling

function print(){
    console.log("Normal")
}
print()

During the compilation a function object is created then it is called with print()

2- Function as an object property

obj = {}
obj.print = function (){
    console.log("Normal")
}
obj.print()

Here a function object is created also but this time the function object as an object property if obj and called using obj.foo()

3- Call function as a constructor using new keyword

function print(){
    console.log("Normal")
}
new print()

similar to first cas but this code is translated to

function print(){
    this = {} // an empty object called *this* is created and returned
    console.log("Normal")
    return {}
}

4- Using call() function

note: if you don't understand wht is this in javascript this may be not understandable for you The fourth way to invoce a function is call the call() function that's propert of any function object

function print(){
    console.log("Normal")
}
print.call()

but why would I use print.call() instead of just print()?

using call() comes with an extra feature that you can pass an object as an argument to bind the function print to this object

5- Self calling function

(function (){
    this = {} // an empty object called *this* is created and returned
    console.log("Normal")
    return {}
})()

once this function is reached it is called, useful if it's used one time

 
Share this