DEV Community

abhsiksah
abhsiksah

Posted on

WHY is this not showing 123???

var status = 23;

function yzx() {
  var status = 123;

  xyz = () => {
    setTimeout(() => {
      console.log(this.status);
    }, 100);
  };
  xyz();
}
yzx();
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
jcubic profile image
Jakub T. Jankiewicz

Because this is not scope only object context. when you call a method x.foo() this inside foo is x. And if you don't have object context like in your example this is window object.

Collapse
 
abhsiksah profile image
abhsiksah • Edited

actually the question is more like if i would have done

var status = 23;

function yzx() {
  this.status = 123;

  console.log(this.status);

  const xyz = () => {
    setTimeout(() => {
      console.log(this.status);
    }, 100);
  };
  xyz();
}
yzx();

Enter fullscreen mode Exit fullscreen mode

then i will get 123 because now i am attaching 123 to this of the function xyz()
but where does a var or let attachs itself to when in a function you can point it at by simply

var status = 23;

function yzx() {
  var status = 123;
console.log(status);
  console.log(this.status);

  const xyz = () => {
    setTimeout(() => {
      console.log(this.status);
    }, 100);
  };
  xyz();
}
yzx();

Enter fullscreen mode Exit fullscreen mode

here we have said console.log(status) and we are able to see 123 in console.log()

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

Check this:

var status = 23;

function yzx() {
  this.status = 123;

  console.log(this.status);

  const xyz = () => {
    setTimeout(() => {
      console.log(this.status);
    }, 100);
  };
  xyz();
}
yzx();
console.log(status); // 123
Enter fullscreen mode Exit fullscreen mode

You're not attaching this to function. Function doesn't have this in this case. This is window (global object) object here. Don't use this outside of object context. You're using legacy behavior that stops working if you use "use strict" that is default for ES Module and web workers.