JS Tutorials
JS Objects
JS Functions
JS Classes
JS Async
The code inside a JavaScript function will
execute when "something" invokes it.
The code inside a function is not executed when the function is defined.
The code inside a function is executed when the function is invoked.
It is common to use the term "call a function" instead of "invoke a function".
It is also common to say "call upon a function", "start a function", or "execute a function".
In this tutorial, we will use invoke, because a JavaScript function can be invoked without being called.
The function above does not belong to any object. But in JavaScript there is always a default global object.
In HTML the default global object is the HTML page itself, so the function above "belongs" to the HTML page.
In a browser the page object is the browser window. The function above automatically becomes a window function.
myFunction() and window.myFunction() is the same function:
This is a common way to invoke a JavaScript function, but not a very good practice.
Global variables, methods, or functions can easily create name conflicts and bugs in the
global object.
In JavaScript, the thing called this, is the object that
"owns" the current code.
The value of this, when used in a function, is the object
that "owns" the function.
Note that this is not a variable.
It is a keyword. You cannot change the value of this.
Tip: Read more about the this keyword
When a function is called without an owner object, the value of this
becomes the global object.
In a web browser the global object is the browser window.
This example returns the window object as the value of this:
Invoking a function as a global function, causes the value of this to be
the global object.
Using the window object as a variable can easily crash your program.
In JavaScript you can define functions as object methods.
The following example creates an object (myObject), with two properties (firstName and lastName), and a method (fullName):