In the simplest term “this” refer to itself, the class object it lives in.
When file is written and when its read by the browser “this” typically refers to the browser window object.
this.alert(‘hello’) is the same as window.alert(‘hello’)
//Some example.js file
// code
console.log(this)
// more code
function first(){
console.log('first', this)
}
first()
The console.log will log out
Window {0: Window, window: Window, self: Window, document: document, name: '', location: Location, …}`
first
Window {0: Window, window: Window, self: Window, document: document, name: '', location: Location, …}
Shouldn’t the `console.log(‘first’, this)` be scoped to the first() function? Yes, it is scoped. It’s still under the browser window class. Inside the window class object we also have the first() function. Once again “this” refer to the class object itself.
We can change “this” by creating our own class object.
class Player {
// the constructor always runs first creating these properties for every new Player
constructor(name, type){
console.log('player', this) // player Player{}
this.name = name
this.type = type
console.log('player', this) // player Player{ name: 'Wizzy', type: 'Fire Mage' }
}
// create another property in the Player object
introduce() {
console.log(`Hi I am ${this.name}, I am a ${this.type}`)
}
}
const player1 = new Player('Wizzy', 'Fire Mage')
Now ‘this’ does not refer to the window object anymore but our newly created Player class object.
console.log(player1.name)
console.log(player1.type)
player1.introduce()
We can even extend this class to another class.
class Wizard extends Player {
//all new class needs a constructor
constructor(name, type){
//require super to get access to parent constructor properties
super(name, type)
console.log('wizard', this) // wizard Wizard { name: 'Freezer', type: 'Ice Mage' }
}
//another property in the Wizard object
play() {
console.log(`Boom I'm a ${this.type}`)
}
}
const wizard1 = new Wizard('Freezer', 'Ice Mage')
In this case, ‘this’ now refer to the new class Wizard. In addition to all its properties from the Wizard class, it also inherit all the properties from its parent class as well.
console.log(wizard1.name)
console.log(wizard1.type)
wizard1.play()
wizard1.introduce()
This was brief, hope it helped somewhat.