Hello, today i was reading about this, you ask what I say this is a keyword in JavaScript which refers to ......?
Well this
is a question we will try to answer today.
Code 1 - Implicit binding
this.name = 'Global Name';
const person = {
name: 'James Bond',
profession: 'Agent',
id: '007'
hi: function() {
return this.name
}
}
person.hi() // 'James Bond'
Well, clearly this refers to its immediate object.
Now lets change this a little bit
this.name = 'Global Name';
const person = {
name: 'James Bond',
profession: 'Agent',
id: '007'
hi: () => {
return this.name
}
}
person.hi() // 'Global Name'
If you see clearly I have changed hi
key's value to an arrow function and arrow functions changes the reference this
to global object. But why ? can you answer in comments ?
Code 2 - Explicit binding
this.name = 'Global Name';
const person = {
name: 'James Bond',
profession: 'Agent',
id: '007'
hi: function() {
return this.name
}.bind(window)
}
person.hi() // 'Global Name'
In here this
will refer to global object since we have bind it to window object which is the global object.
Thank you
Top comments (0)