DEV Community

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

Posted on

2

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools canโ€™t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay