Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
38
rated 0 times [  45] [ 7]  / answers: 1 / hits: 95260  / 11 Years ago, fri, november 8, 2013, 12:00:00

When I type this in node.js, I get undefined.



var testContext = 15;
function testFunction() {
console.log(this.testContext);
}
testFunction();
=>undefined


Without var keyword, it passes (=>15). It's working in the Chrome console (with and without var keyword).


More From » node.js

 Answers
42

It doesn't work in Node when using var because testContext is a local of the current module. You should reference it directly: console.log(testContext);.



When you don't type var, what happens is that testContext is now a global var in the entire Node process.



In Chrome (or any other browser - well, I'm unsure about oldIE...), it doesn't matter if you use var or not in your example, testContext will go to the global context, which is window.



By the way, the global context is the default this of function calls in JS.


[#74416] Thursday, November 7, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raymondorlandok

Total Points: 530
Total Questions: 110
Total Answers: 96

Location: Lebanon
Member since Wed, Dec 21, 2022
1 Year ago
raymondorlandok questions
;