JavaScript Function Invocation

JavaScript functions can be called in 4 ways.

The difference between each method is the initialization of this .

The this Keyword

In general, in Javascript, this refers to the current object when the function is executed.

Note: that this is a reserved keyword and you cannot modify the value of this.

Calling JavaScript functions

In the previous chapters we have learned how to create functions.

The code in the function is executed after the function is called.

Called as a function


function myFunction (a, b) { return a * b; } myFunction (10, 2); //myFunction (10, 2) returns 20
Try it Yourself »

The above functions do not belong to any object. But it is always the default global object in JavaScript.

The default global object in HTML is the HTML page itself, so functions belong to HTML pages.

The page object in the browser is the browser window (window object). The above function will automatically become a function of the window object.

myFunction () is the same as window.myFunction ():


function myFunction (a, b) { return a * b; } window.myFunction (10, 2); //window.myFunction (10, 2) returns 20
This is a common method for calling JavaScript functions, but it is not good programming practice Global variables, methods, or functions are prone to naming conflict bugs.

The Global Object

The value of this becomes a global object when the function is not called by its own object.

The global object in a web browser is the browser window (window object).

This instance returns the value of this as a window object:


function myFunction () { return this; } myFunction (); //returns window object
Try it Yourself »
Calling the function as a global object makes the value of this a global object. Using a window object as a variable can easily cause a program to crash.

Function is called as a method

In JavaScript you can define functions as methods of objects.

The following example creates an object ( myObject ), the object has two properties ( firstName and lastName ), and a method (< strong> fullName ):


var myObject = { firstName: "John", lastName: "Doe", fullName: function () { return this.firstName + "" + this.lastName; } } myObject.fullName (); //returns "John Doe"
Try it Yourself »

fullName method is a function. Functions belong to objects. myObject is the owner of the function.

this object with JavaScript code. The value of this in the example is a myObject object.

Test the following! Modify the fullName method and return the this value:


var myObject = { firstName: "John", lastName: "Doe", fullName: function () { return this; } } myObject.fullName (); //returns [object Object] (owner object)
Try it Yourself »
A function is called as an object method, making the value of this the object itself.