-1

I read somewhere that in JS function (not the function), the scope of this keyword depends on the parent object calling it.

So I did something as simple as declaring a variable name in my Global Scope and calling it inside a function using this keyword

let name = "rohit" 

function something () {
console.log("this scope", this.name) 
}

something()

This didn't logged anything for this.name

Question: Can someone help me understand that why does it not log anything and not even return an error?

anny123
  • 4,763
  • 6
  • 30
  • 72
  • Hint: what is the object context of the call to `something`... – Jared Smith Jan 02 '19 at 12:31
  • If you are calling `something()`, `this` will be `undefined`, at least in strict mode. Don't try to get the global object through that. (Which, btw, only has a [`.name`](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) but [not your `let name`](https://stackoverflow.com/q/28776079/1048572)) – Bergi Jan 02 '19 at 12:33
  • Because you have declared your variable with let and that simply have block level scope. Inside the function, you can not access outside let variable. – Mohit Saxena Jan 02 '19 at 13:26

1 Answers1

1

Inside function unless explicitly bound, this refers to window. So remove let keyword and name will be available in window

name = "rohit"

function something() {
  console.log("this scope", this.name)
}

something()
brk
  • 43,022
  • 4
  • 37
  • 61