The this Keyword
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.
The code in a function is not executed when the function is defined. It is executed when the function is invoked.
Some people use the term "call a function" instead of "invoke a function".
It is also quite common to say "call upon a function", "start a function", or "execute a function".
Invoking a Function as a Function
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:
The Global Object
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.
Invoking a Function as a Method
The following example creates an object (myObject), with two properties (firstName and lastName), and a method (fullName):
The fullName method is a function. The function belongs to the object. myObject is the owner of the function.
Test it! Change the fullName method to return the value of this:
Invoking a function as an object method, causes the value of this to be the object itself.
Invoking a Function with a Function Constructor
If a function invocation is preceded with the new keyword, it is a constructor invocation.
A constructor invocation creates a new object. The new object inherits the properties and methods from its constructor.
The this keyword in the constructor does not have a value. The value of this will be the new object created when the function is invoked.
Invoking a Function with a Function Method
Both methods take an owner object as the first argument. The only difference is that call() takes the function arguments separately, and apply() takes the function arguments in an array.
In "non-strict" mode, if the value of the first argument is null or undefined, it is replaced with the global object.
With call() or apply() you can set the value of this, and invoke a function as a new method of an existing object.