1

logging "this" logs the contents of the global object but "this.name" logs undefined instead of "kenny". I am using node to execute the script

var name = "kenny";

function nameLogger() {
    console.log(this);        //is logging the global object
    console.log(this.name);   //undefined
}

nameLogger();
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
Kenny Omega
  • 398
  • 2
  • 12
  • What are you expecting? `this` refers to the function scope, in which there's no `name` property. – Phix May 02 '18 at 15:55
  • Why are you trying to store values in the global scope in Node? – JLRishe May 02 '18 at 15:56
  • 1
    If I evaluate that code in Node, it logs `kenny` to the console after it logs the global object. The `undefined` you are seeing is the return value of the `nameLogger()` function call. – JLRishe May 02 '18 at 16:01
  • @Phix "this" does not refer to the function scope, it refers to the global scope, cause the call to nameLogger() is done from global scope – Kenny Omega May 02 '18 at 19:53
  • @JLRishe yes inside node it is working, but if i store this script in a file say "script.js" and run it using node, "node script.js", then it is logging undefined and i can't think as to why that is happening. I tried on multiple systems, does not work. Please see if you can help. Thanks in advance – Kenny Omega May 02 '18 at 19:59
  • @KennyOmega Ok, in a node script, variables are scoped to the script and not added to the global object. So your issue is not with the behavior of `this`, but with the behavior of `var`. What are you trying to accomplish? – JLRishe May 03 '18 at 13:07
  • @JLRishe thank you, i did not know about that behaviour of node. I was trying to bind the this to the global object and it worked in browser but did not work in node. Once again, thanks for the clarification – Kenny Omega May 14 '18 at 12:18

0 Answers0