What is “this” in Javascript?

What is “this” in Javascript – especially, when you use bind( ), arrow function and regular function?

  this refers to its closest object.


Maya, you’re not making any sense!

Wait, let me explain. 


If this is called in a global scope, then this refers to “window” object in a browser or “global” object in Node.

function checkThis() {
  return this;
}

// In a browser:
checkThis() === window; // true 

// In Node:
checkThis() === global; // true

But what other things that could be inside this ?

The answer is, well … whatever the object is.

this is but an alias to the actual object. See below, this is equivalent to user.

let user = {
  name: "Maya",
  age: 30,

  callMe() {
    alert(this.name);
    alert(user.name);
  }

};

user.callMe(); // will output "Maya", and then "Maya" again

That’s it?

Wait, there is more! 

this is defined or evaluated during run-time. The moment you create or write this, this is just a concept or a keyword in the ocean of your codebase (that you expect to work and mean something, of course). But only when the function runs, this will turn into an object (or undefined, when there is no object in its outer scope and when the code is set to be in a strict mode).

let human = { name: "Maya" };
let dog = { name: "Pillow" };

function sayHi() {
  alert( this.name );
}

// register the function in two objects
human.sayHi = sayHi;
dog.sayHi = sayHi;

When we call sayHi() on two different objects (human and dog), this is a different object each time.

this inside the following function is the object “before the dot”

human.sayHi(); // Maya  (this == human)

this inside the following function call is defined “before the opening bracket”

dog['sayHi'](); // Pillow  (this == dog)

*Both function call styles work just the same.

So the meaning of this relies on the scope, its closest object and the run-time of our function then?

Not necessarily. Especially if that is not what you want.


We can actually decide what this should be!

How?

We can tie our this to whatever object we pass in to our bind().

Let’s see two examples of similar code with different names addThis() and noThis(), both run console.log(this);

function addThis() {
  console.log(this) // 'this' = "hello" because it is bound to "hello"
}


function noThis() {
  console.log(this); // 'this' = window object
}

let runMe = addThis.bind("hello"); // ties "hello" to addThis

runMe(); // executes addThis and returns "hello" 

noThis(); // executes noThis and returns a window object 

Metaphorically, bind() is like the matchmaker that sets up your girl friend (the this) with a guy (the Object). We use bind’s matchmaking service, so she (this) will not end up with some random guys (the window guys, the global guys, the undefined guys – because heaven forbid; or some other guys who are not good for her (wrong objects that wreak havoc the code).

But what about a function that lives inside a function that is already bound to an object?

Will that inner function inherit the bound object of its parent’s function?

The answers are : YES AND NO.

Yes, if the inner function is an arrow function.

Because this type of function does not have its own this, but will latch on to any object that its parent is bound to (a Window object if the arrow lives in the global scope).

No, if the inner function is a function that uses function keyword.

Because, this type of function, will lose its binding / object context and back to refer to the window object again.

function parentFunc() {
  console.log(this) // 'this' = "hello"
  
  childFuncArrow = () => { 
     console.log(this); // 'this' = "hello"
  };

  childFuncArrow();

   
  function childFuncNormal() {
     console.log(this); // 'this' = the window object - oh no!
  }

  childFuncNormal();
  
}

let runMe = parentFunc.bind("hello"); 

runMe(); // execute parentFunc which outputs "hello", "hello", window object

Even if we don’t use bind(), inner arrow function will always take its this from the nearest object – which in this case is bound to the arrow function by its normal function parent, the twoFunctions(). But inner normal function will lose its context.

The example below, shows an arrow function’s this as the human object (its direct parent’s this) and the normal function will return undefined.

let human = {

  name: "Maya",
  
  twoFunctions() {

    console.log(this.name); //  output "Maya"

    let arrow = () => console.log(this.name); // output "Maya"

    arrow();
    
    function notArrow() {
      console.log(this.name); // output "undefined" - because it tries to call window.name
    }
 
    notArrow();
  },
}
  
human.twoFunctions(); // Will output "Maya" and "undefined"

109 Comments

  1. Jgsvjarly January 1, 2021 at 6:14 am

    viagra online mastercard wildviagra generic viagra soft tabs

  2. naim izle January 19, 2021 at 10:49 am

    Respect to post author, some wonderful information . Agnesse Harcourt Haney

  3. free porn January 21, 2021 at 2:28 pm

    Appreciate it for helping out, great information. Tove Waldemar Rainer

  4. 1080p January 29, 2021 at 9:11 pm

    Tremendous issues here. I am very happy to see your article. Otha Clayton Kimberlee

  5. dublaj January 31, 2021 at 11:21 am

    I get very useful information on your page, I feel lucky Pammie Corrie Mireielle

  6. direk January 31, 2021 at 11:01 pm

    You need to take part in a contest for one of the finest sites on the web. Kimberlee Ange Henrie

  7. hindi movie February 1, 2021 at 1:58 pm

    There is visibly a bunch to realize about this. I think you made certain nice points in features also. Shelia Ari Hedwig Abbe Marchall Caritta

  8. dublaj February 1, 2021 at 9:42 pm

    Hi my family member! I wish to say that this article is amazing, nice written and include almost all significant infos. I would like to look more posts like this. Rosaline Weber Amory

  9. Shell Upload Bypass February 3, 2021 at 2:56 am

    What i don’t understood is in truth how you are not really much more
    smartly-liked than you may be now. You’re very intelligent.
    You understand thus considerably relating to this topic, produced me individually imagine
    it from a lot of numerous angles. Its like men and women don’t
    seem to be interested unless it is one thing to do with Girl gaga!
    Your personal stuffs outstanding. Always care for it
    up!

  10. antalyanın haber sitesi February 3, 2021 at 7:34 am

    I’m gone to tell my little brother, that he should also pay a
    visit this blog on regular basis to get updated from latest information.

  11. 720p February 6, 2021 at 5:02 pm

    I in addition to my pals were found to be viewing the great procedures found on the website and then got an awful feeling I had not thanked the site owner for those tips. Most of the young boys were stimulated to see them and have actually been tapping into those things. Appreciation for genuinely well accommodating and then for going for certain notable subject matter most people are really needing to discover. Our own sincere regret for not expressing gratitude to sooner. Sallyann Theodor Allveta

  12. 720p February 6, 2021 at 5:23 pm

    Incredible quest there. What occurred after? Take care!| Dreddy Frasier Naarah

  13. movie online February 6, 2021 at 7:16 pm

    The cleaning firm executes cleaning of areas of different sizes and also configurations. Anthea Orv Liva

  14. 123movies February 6, 2021 at 11:34 pm

    You could certainly see your skills within the work you write. The world hopes for more passionate writers such as you who are not afraid to mention how they believe. All the time follow your heart. Kara-Lynn Gunar Plossl

  15. movie download February 7, 2021 at 1:03 am

    Hi guys, I am Jherry Hogan an expert in report writing. Lauraine Ermin Rochester Nathalia Rory Mroz

  16. online February 7, 2021 at 1:03 am

    Along with almost everything that appears to be building throughout this particular subject material, all your perspectives are generally quite stimulating. Nonetheless, I am sorry, but I do not subscribe to your entire theory, all be it refreshing none the less. It appears to us that your remarks are actually not entirely validated and in simple fact you are your self not totally certain of your assertion. In any case I did appreciate looking at it. Konstance Gregorio Harhay

  17. turkce February 13, 2021 at 11:23 am

    Is there a Marlin command that will identify which drivers are installed on a mainboard? Ronnica Ansell Clotilde

  18. MichaelEscom March 9, 2021 at 4:22 pm

    generic pills for ed cheap tadalafil

  19. retinol serum March 10, 2021 at 9:43 am

    Howdy just wanted to give you a quick heads up. The words in your article seem to be running off the screen in Chrome.
    I’m not sure if this is a formatting issue or something to do with browser compatibility
    but I figured I’d post to let you know. The layout look great though!

    Hope you get the problem fixed soon. Cheers

  20. MichaelEscom March 10, 2021 at 2:16 pm

    generic pills: https://genericwdp.com/ pills without a doctor prescription

  21. ventolin reviews March 13, 2021 at 12:20 am

    albuterol ventolin hfa ventolin inhaler relion ventolin hfa inhaler 2018 what is going to replace ventolin for people that have asthma

  22. Jeffreytoise March 14, 2021 at 10:45 am

    buy viagra online usa viagra online usa
    where can i buy viagra over the counter

  23. Stanleypot March 16, 2021 at 4:54 pm

    propecia buy online propecia sale

  24. ynuxxrjbsb March 20, 2021 at 5:00 pm

    Muchas gracias. ?Como puedo iniciar sesion?

  25. clomid source March 21, 2021 at 7:25 am

    clomid 100 mg clomid price clomid side effects after ovulation how long does clomid take to work for men

  26. ElmerFloow March 23, 2021 at 10:06 pm

    buy ed pills from canada buy ed drugs
    ed pills without a doctor prescription

  27. takipci satin al March 28, 2021 at 9:47 am

    I like the valuable information you supply on your articles.
    I’ll bookmark your blog and check again here regularly.
    I am quite sure I’ll be told many new stuff right here!
    Best of luck for the next!

  28. antalya izolasyon March 28, 2021 at 7:01 pm

    May I simply just say what a relief to discover a person that actually understands what they’re talking about over the internet.

    You actually realize how to bring a problem to
    light and make it important. More people have to check this out and understand this side of the story.
    I was surprised that you’re not more popular because you certainly have
    the gift.

  29. instagram taki̇pçi̇ satin al ucuz March 28, 2021 at 8:08 pm

    Hi there! Quick question that’s totally off topic. Do you know how to make
    your site mobile friendly? My website looks weird when browsing from my
    iphone4. I’m trying to find a theme or plugin that might be able to resolve this problem.

    If you have any recommendations, please share. Thanks!

  30. takip2018 March 29, 2021 at 5:17 am

    Magnificent goods from you, man. I have understand your stuff previous to and you’re just too great.

    I actually like what you’ve acquired here, certainly like what you’re stating and the way in which you say it.
    You make it enjoyable and you still take care of to keep it
    wise. I can not wait to read far more from you. This is really a wonderful site.

  31. güvenilir takipçi satın al April 1, 2021 at 4:13 am

    Wonderful article! This is the type of info that
    are supposed to be shared across the internet.
    Shame on Google for no longer positioning this publish upper!
    Come on over and seek advice from my site . Thanks =)

  32. Tik tok takipçi satın al April 1, 2021 at 11:07 am

    Sosyal medya platformları arasında büyük bir kitleye sahip olan TikTok,
    birçok kişinin ilgisini toplayan bir platform olmayı başardı.

    Uygulama aracılığı ile birçok insana videosunu ulaştıran kişiler, beğeni toplayarak kendi profillerini tanınmış bir hale getirmek için uğraşıyorlar
    TikTok Takipçi Satın Al Konusunda
    uzman kadrosu ile sizleride popüler etmek için var !

  33. Billybib April 8, 2021 at 11:22 pm

    pills for erectile dysfunction: viagra pills online viagra pills online

  34. asmr https://0mniartist.tumblr.com April 10, 2021 at 9:38 am

    We stumbled over here from a different web address and thought I may
    as well check things out. I like what I see so now i am following you.

    Look forward to looking into your web page yet again. asmr 0mniartist

  35. asmr https://0mniartist.tumblr.com April 10, 2021 at 12:12 pm

    Hi, I think your site might be having browser compatibility issues.
    When I look at your website in Ie, it looks fine but when opening
    in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that, very good blog!

    0mniartist asmr

  36. asmr https://0mniartist.tumblr.com April 11, 2021 at 3:02 am

    wonderful submit, very informative. I’m wondering why
    the opposite specialists of this sector don’t notice this.
    You should proceed your writing. I am sure, you have a great readers’ base already!
    0mniartist asmr

  37. asmr https://0mniartist.tumblr.com April 11, 2021 at 4:44 am

    Please let me know if you’re looking for a article author for your blog.
    You have some really good posts and I believe I would
    be a good asset. If you ever want to take some of the load off,
    I’d absolutely love to write some material for your blog in exchange for a link back
    to mine. Please blast me an e-mail if interested.
    Thanks! asmr 0mniartist

Leave a comment

Your email address will not be published. Required fields are marked *