0
let a = {
  X: 'Hello',
  Y: function(){
    console.log(this.X) // Hello
  }
}

why we need to use keyword 'this' to access X

why not access it directly like variable without this.

DrfArch
  • 41
  • 1

1 Answers1

2

this = object scope and no this window scope

Try this.

var X = "Out hello";
let a = {
  X: 'Hello',
  Y: function () {
  //console.log(self);    // the window object
    console.log(this);    // the {X,Y} object itself
    console.log(X);       // Out hello
    console.log(this.X);  // Hello
  }
}
a.Y();
.as-console-wrapper { min-height: 100%!important; top: 0; }
Peter Seliger
  • 4,001
  • 1
  • 20
  • 27
gillall
  • 101
  • 1
  • 7