this
inside
driveCar()
function refers to the global window object.
Global variables
firstName
and
lastName
are added to the
window
object.
That is why they are visible using the keyword
firstName = "Jack"
lastName = "Ma"
function driveCar() {
document.write(this.firstName + ' ' + this.lastName + ' is driving a car<br/>')
}
driveCar()
If we call the same function using
call
function,
this
will refer to the object that will be passed.
In this case:
john
object
let john = {
firstName: 'John',
lastName: 'Doe'
}
function driveCar() {
document.write(this.firstName + ' ' + this.lastName + ' is driving a car<br/>')
}
driveCar.call(john)