Inside a method defined using a function() {}
syntax we have access to the object instance by using this
.
This is one of the concepts that confuse JavaScript developers the most.
this
is a keyword that has different values depending on where it’s used, but there’s just one place where it makes sense to use this
: INSIDE OBJECT METHODS.
A method, as you know, is a function attached to an object.
You know that functions have two forms:
- regular functions
- arrow functions
If you need to reference the object instance from within a method, you can’t use arrow functions. You have to use regular functions.
That’s one of the few places where regular functions can’t be replaced with arrow functions.
In the following example, we have access to the brand
and model
properties values using this.brand
and this.model
:
const car = {
brand: "Ford",
model: "Fiesta",
start: function () {
console.log(`Started
${this.brand} ${this.model}`)
},
}
car.start()
//Started Ford Fiesta
It’s very important to note this distinction between regular functions and arrow functions: we don’t have access to this
if we use an arrow function:
const car = {
brand: "Ford",
model: "Fiesta",
start: () => {
console.log(`Started
${this.brand} ${this.model}`)
},
}
car.start()
//'Started undefined undefined'
This is because arrow functions are not bound to the object, and that’s why regular functions are often used as object methods.