@jgCarroll/

thisKeyword

JavaScript

A common interview question: What is the 'this' keyword in Javascript, and how does it work?

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// const house = {
//   price: 100000,
//   squareFeet: 2000,
//   owner: 'Taylor',
//   getPricePerSquareFoot: function() {
//     return house.price / house.squareFeet
//   }
// }
// console.log(house.price)
// console.log(house.getPricePerSquareFoot())

// ============================
// rewritten with the 'this' keyword

const house = {
  price: 100000,
  squareFeet: 2000,
  owner: 'Taylor',
  getPricePerSquareFoot: function() {
    return this.price / this.squareFeet
  }
}
console.log(house.price)
console.log(house.getPricePerSquareFoot())
Native Browser JavaScript