1. Intro to `this` Keyword
A Definition for this
In JavaScript, the keyword this
refers to the object that called (or invoked) the function (that's the simplest definition). The trick with this
is that it is defined when the function is invoked, not when it is written. What does that mean?
Copy/paste the following example in your console:
var counter = {
count: 0,
updateCounter: function () {
this.count += 1;
},
};
counter.updateCounter();
counter.updateCounter();
counter.updateCounter();
alert(counter.count);
In this example, counter
invoked (or called) the updateCounter
function. This increments counter
's count
property. Inside the updateCounter
method, the "this.count
" is the same as the alerted "counter.count
", Or in other "words", we can say this === counter
(the object that invoked the function).
Let's look at another:
var cat = {
makeNoise: function () {
alert(this.noise);
},
noise: "Meow!",
};
var dog = {
makeNoise: cat.makeNoise,
noise: "Woof!",
};
cat.makeNoise();
dog.makeNoise();
At first glance, you might be tempted to assume that "Meow!" will alert two times and "Woof!" will not alert at all. But let's break it down:
When cat.makeNoise()
is called, this.noise
is the same thing as cat.noise
. Then, when dog.makeNoise()
is called, this
changes because it refers to the object that called the function. Now it refers to dog
instead of cat
, therefore this.noise
is the same as cat.noise
. Here's a diagram to illustrate:
Here's another way to write it with the same result:
var makeNoiseFunction = function () {
alert(this.noise);
};
var cat = {
makeNoise: makeNoiseFunction,
noise: "Meow!",
};
var dog = {
makeNoise: makeNoiseFunction,
noise: "Woof!",
};
cat.makeNoise();
dog.makeNoise();
this
Exercise 1
Copy/paste the following code in your console. Fix the errors to make it work:
var person = {
hungry: true,
feed: function () {
if (hungry) {
hungry = false;
alert("Im no longer hungry!");
}
},
};
person.feed();
See Answer
var person = {
hungry: true,
feed: function () {
if (this.hungry) {
this.hungry = false;
alert("Im no longer hungry!");
}
},
};
person.feed();
this
Exercise 2
Copy/paste the following code in your console. Fix the errors to make it work. There is 1 logic error and 2 syntax errors:
var pump = function (amount) {
liters += amount;
console.log('You put ' + amount + ' liters in ' + this.name);
};
var garage = {
car1: {
name: 'Audi',
liters: 3,
fillTank: pump
}
car2: {
name: 'Mercedes',
liters: 1
fillTank: pump
}
};
garage.car1.fillTank(2);
console.log('Audi should have 5 liters: ', garage.car1.liters);
garage.car2.fillTank(30);
console.log('Mercedes should have 31 liters: ', garage.car2.liters);
See Answer
var pump = function (amount) {
this.liters += amount;
console.log("You put " + amount + " liters in " + this.name);
};
var garage = {
car1: {
name: "Audi",
liters: 3,
fillTank: pump,
},
car2: {
name: "Mercedes",
liters: 1,
fillTank: pump,
},
};
garage.car1.fillTank(2);
console.log("Audi should have 5 liters: ", garage.car1.liters);
garage.car2.fillTank(30);
console.log("Mercedes should have 31 liters: ", garage.car2.liters);
this
Exercise 3
Copy/paste the following code in your console. Fix 2 logic errors:
var pumpFuel = function (plane) {
plane.fuel += 1;
};
var airplane = {
fly: function () {
if (fuel < 2) {
return "on the ground!";
} else {
return "flying!";
}
},
};
console.log("The plane should not be able to fly (yet): " + airplane.fly());
pumpFuel(airplane);
console.log("The plane should STILL not be able to fly: " + airplane.fly());
pumpFuel(airplane);
console.log("Can it fly now? " + airplane.fly());
See Answer
var pumpFuel = function (plane) {
plane.fuel += 1;
};
var airplane = {
fuel: 0,
fly: function () {
if (this.fuel < 2) {
return "on the ground!";
} else {
return "flying!";
}
},
};
console.log("The plane should not be able to fly (yet): " + airplane.fly());
pumpFuel(airplane);
console.log("The plane should STILL not be able to fly: " + airplane.fly());
pumpFuel(airplane);
console.log("Can it fly now? " + airplane.fly());
this
Exercise 4
Create a method called stealCoins
that takes a number parameter and decreases the tipJar
's coins by that amount:
var tipJar = {
coinCount: 20,
tip: function () {
this.coinCount += 1;
},
};
tipJar.tip();
console.log("Wishing well should have 21 coins: " + tipJar.coinCount);
tipJar.stealCoins(3);
console.log("Wishing well should have 18 coins: " + tipJar.coinCount);
tipJar.stealCoins(10);
console.log("Wishing well should have 8 coins: " + tipJar.coinCount);
See Answer
var tipJar = {
coinCount: 20,
tip: function () {
this.coinCount += 1;
},
stealCoins: function (num) {
this.coinCount -= num;
},
};
tipJar.tip();
console.log("Wishing well should have 21 coins: " + tipJar.coinCount);
tipJar.stealCoins(3);
console.log("Wishing well should have 18 coins: " + tipJar.coinCount);
tipJar.stealCoins(10);
console.log("Wishing well should have 8 coins: " + tipJar.coinCount);
this
Exercise 5
The code below has a few problems. Fix the 3 syntax errors and 1 logical error. The flow of this is really tricky, so take it slow and write it out if you need to:
var revealSecret = function () {
return secret;
};
var shoutIt = function (person, func) {
person.revealItAll = func;
var result = person.revealItAll();
alert(person.name + " said: " result);
};
var aaron = {
name: "Aaron"
secret: "Im scared of heights!"
};
var sarah = {
name: "Sarah"
secret: "My middle name is Darlene!"
};
shoutIt(aaron, revealSecret);
shoutIt(sarah, revealSecret);
See Answer
var revealSecret = function () {
return this.secret;
};
var shoutIt = function (person, func) {
person.revealItAll = func;
var result = person.revealItAll();
alert(person.name + " said: " + result);
};
var aaron = {
name: "Aaron",
secret: "Im scared of heights!",
};
var sarah = {
name: "Sarah",
secret: "My middle name is Darlene!",
};
shoutIt(aaron, revealSecret);
shoutIt(sarah, revealSecret);