Objects · Lesson 25 of 45
Methods and this
Functions inside objects, and what this points to.
8 minutes3 games
A function inside an object is a method. Inside it, this refers to the object the method was called on (whatever is before the dot).
JavaScript
const account = {
owner: "Hana",
balance: 500,
deposit(amount) {
this.balance += amount
return this.balance
},
describe() {
return `${this.owner} has ${this.balance} EGP`
},
}
account.deposit(250)
console.log(account.describe())JavaScript
const timer = {
seconds: 3,
regular() { return typeof this.seconds },
arrow: () => typeof this,
}
console.log(timer.regular()) // number
console.log(timer.arrow()) // not the timer objectWhat's the output?
const dog = {
name: "Rex",
speak() {
return this.name + " barks"
},
}
console.log(dog.speak())What will this code print?
Complete the code
Complete the method so it returns the full name.
const person = { first: "Mona", last: "Adel", full() { return .first + " " + .last }, }
Exercise
Add an area method returning width * height, then print it (24).
Expected output: 24
JavaScript
const rect = {
width: 4,
height: 6,
}
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.