this
inside
fn()
function refers to the global
window
object.
That is why
firstName
and
lastName
attributes are not accessible using
this
keyword
let john = {
firstName: 'John',
lastName: 'Doe',
driveCar() {
function fn () {
console.log(this.firstName + ' ' + this.lastName + ' is driving a car'); // "undefined undefined is driving a car"
console.log(this);
}
fn(); // fn.call(this);
console.log(this.firstName + ' ' + this.lastName + ' is driving a car');
console.log(this)
}
}
john.driveCar();
In order to fix the issue, one of the ways is to use
call
function and pass the object that we want
this
to refer to inside the
fn()
function
fn.call(this);
Inside
driveCar()
function
this
refers to the
john
object because it is called through
john
object
john.driveCar();