What is "this"
Lixical scope & Dynamic scope
function printName() {
console.log(this)
}
printName()
-----------------------
result = Window
-----------------------
How to know what is "this"?
functin printName() {
console.log(this)
console.log(`My name is ${this.name}`)
}
1 Invoker object
const sam = {name: 'sam', printName}
const my = {name: 'my', printName}
sam.printName()
my.printName()
printName()
----------------------------------------------
result
----------------------------------------------
Object { name: "sam", printName: printName() }
My name is sam
Object { name: "my", printName: printName() }
My name is my
Window
My name is
----------------------------------------------
2 Global object (window, global)
name = 'Global'
printName()
-----------------
result
-----------------
Window
My name is Global
-----------------
3 Constructor function
function Person(name) {
this.name = name
this.printName = printName
}
const my = new Person('My')
my.printName()
----------------------------------
result
----------------------------------
Object { name: "My", printName() }
My name is My
----------------------------------
3 call(), apply(), bind()
function printName(nationality, city) {
console.log(this)
console.log(`My name is ${this.name}, I'm ${nationality} and am living in ${city}`)
}
function Person(name, nationality, city) {
this.name = name
this.nationality = nationality
this.city = city
printName(this.nationality, this.city)
printName.call(this, this.nationality, this.city)
printName.apply(this, [this.nationality, this.city])
const printMy = printName.bind(this)
printMy(this.nationality, this.city)
}
const my = new Person('my', 'thai', 'bangkok')
-----------------------------------------------------------
result
-----------------------------------------------------------
======================================
printName(this.nationality, this.city)
======================================
Window
My name is , I'm thai and am living in bangkok
=================================================
printName.call(this, this.nationality, this.city)
=================================================
Object { name: "my", nationality: "thai", city: "bangkok" }
My name is my, I'm thai and am living in bangkok
====================================================
printName.apply(this, [this.nationality, this.city])
====================================================
Object { name: "my", nationality: "thai", city: "bangkok" }
My name is my, I'm thai and am living in bangkok
====================================
const printMy = printName.bind(this)
printMy(this.nationality, this.city)
====================================
Object { name: "my", nationality: "thai", city: "bangkok" }
My name is my, I'm thai and am living in bangkok
-----------------------------------------------------------