<button onclick="this.style.display='none'">
Click to Remove Me!
</button>
"use strict";
function myFunction() {
return this;
}
// returns undefined because we have used strict which doesn't allow default modefunction myFunction() {
return this;
}
[object Window]:
var x = this;
x // [object Window]
fullName : function() {
return this.firstName + " " + this.lastName;
}
In an object method, this refers to the "owner" of the method.
The person object is the owner of the fullName method.
In a method, this refers to the owner object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call(), and apply() can refer this to any object.
// window is the object that all global variables and functions are defined on, hence:
window.showFullName (); // Peter Ally
// "this" inside the showFullName () method that is defined inside the person object still refers to the person object, hence:
person.showFullName (); // Penelope Barrymore
var person = {
firstName :"Penelope",
lastName :"Barrymore",
showFullName:function () {
// "this" on the line below refers to the person object, because the showFullName function will be invoked by person object.
console.log (this.firstName + " " + this.lastName);
}
}
showFullName (); // Peter Ally
person.showFullName() // Penelope Barrymore
var firstName = "Peter",
lastName = "Ally";
function showFullName () {
// "this" inside this function will have the value of the global variables
// because the showFullName () function is defined in the global scope, just like the firstName and lastName
console.log (this.firstName + " " + this.lastName);
}
var person = {
firstName :"Penelope",
lastName :"Barrymore",
// Since the "this" keyword is used inside the showFullName method below, and the showFullName method is defined on the person object,
// "this" will have the value of the person object because the person object will invoke showFullName ()
showFullName:function () {
console.log (this.firstName + " " + this.lastName);
}
}
person.showFullName (); // Penelope Barrymore