3 JavaScript Function Invocation (The This Keyword)
3 JavaScript Function Invocation (The This Keyword)
Note that this is not a variable. It is a keyword. You cannot change the value of this.
Example
function myFunction(a, b) {
return a * b;
}
window.myFunction(10, 2); // window.myFunction(10, 2) will also return 20
Try it Yourself
This is a common way to invoke a JavaScript function, but not a good practice in computer programming.
Global variables, methods, or functions can easily create name conflicts and bugs in the global object.
Example
function myFunction() {
return this;
}
myFunction();
// Will return the window object
Try it Yourself
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.
Example
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName();
// Will return "John Doe"
The fullName method is a function. The function belongs to the object. myObject is the owner of the function.
The thing called this, is the object that "owns" the JavaScript code. In this case the value of this is myObject.
Test it! Change the fullName method to return the value of this:
Example
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this;
}
}
myObject.fullName();
Try it Yourself
Invoking a function as an object method, causes the value of this to be the object itself.
Example
// This is a function constructor:
function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
}
// This creates a new object
var x = new myFunction("John","Doe");
x.firstName;
// Will return "John"
Try it Yourself
A constructor invocation creates a new object. The new object inherits the properties and methods from its
constructor.
Example
function myFunction(a, b) {
return a * b;
}
myFunction.call(myObject, 10, 2);
// Will return 20
Example
function myFunction(a, b) {
return a * b;
}
myArray = [10,2];
myFunction.apply(myObject, myArray); // Will also return 20
Both methods takes 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 JavaScript strict mode, the first argument becomes the value of this in the invoked function, even if the
argument is not an object.
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.
Previous
Next Chapter