Contoh Lainnya untuk this
var firstName = "Peter",
lastName = "Ally";
function showFullName() {
// "this" inside this function will have the value of the window object
// 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",
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
// 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
Dan pada jQuery
// We have a simple object with a clickHandler method that we want to use when a button on the page is clicked
var user = {
data: [{
name: "T. Woods",
age: 37
},
{
name: "P. Mickelson",
age: 43
}
],
clickHandler: function(event) {
var randomNum = ((Math.random() * 2 | 0) + 1) - 1; // random number between 0 and 1
// This line is printing a random person's name and age from the data array
console.log(this.data[randomNum].name + " " + this.data[randomNum].age);
}
}
// The button is wrapped inside a jQuery $ wrapper, so it is now a jQuery object
// And the output will be undefined because there is no data property on the button object
$("button").click(user.clickHandler); // Cannot read property '0' of undefined
Jika kode tersebut di eksekusi, this pada console.log() akan mendapatkan properti $("button") _karena, _user.clickHandler _dipanggil oleh metode _click dari $("button"). Agar tidak terjadi kesalahan referensi, ada beberapa solusi, salah satunya adalah menggunakan bind() pada clickHandler() yaitu seperti berikut
$("button").click (user.clickHandler.bind (user)); // P. Mickelson 43