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
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