DEV Community

Cover image for Implicit Explicit and....?
Gajender Tyagi
Gajender Tyagi

Posted on

Implicit Explicit and....?

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'

Enter fullscreen mode Exit fullscreen mode

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'

Enter fullscreen mode Exit fullscreen mode

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'

Enter fullscreen mode Exit fullscreen mode

In here this will refer to global object since we have bind it to window object which is the global object.

Thank you

Discussion (0)