4

In node, how come I get undefined in this example ?

Since I am not using strict mode, this should be accessible from inside a function and equal to the Global object.

this.foo = "bar";

function fun () {
    console.log(this.foo);
}

fun(); // undefined
Lev
  • 7,096
  • 11
  • 30
  • 63

1 Answers1

0

See this fragment about "use strict" mode in MDN.

First, the value passed as this to a function in strict mode is not forced into being an object (a.k.a. "boxed"). For a normal function, this is always an object: either the provided object if called with an object-valued this; the value, boxed, if called with a Boolean, string, or number this; or the global object if called with an undefined or null this... for a strict mode function, the specified this is not boxed into an object, and if unspecified, this will be undefined:

For a best explanation and examples, see the reference: "Securing" JavaScript (MDN)

Also see this post in stackoverflow: In node.js, how the 'use strict' statement is interpreted?

Community
  • 1
  • 1
jherax
  • 5,038
  • 5
  • 32
  • 47