javascript "this" keyword works as expected in browser but not in node.js -


i know i'm making mistake here can't figure out is.

the following code (non-strict mode) works expect in browser , outputs "hello" console.

function a() {     console.log(this.bar); } var bar = "hello"; a(); 

but when run in node "undefined" output.

does know reason?

in both, browser , node, this inside function refers global object (in case). every global variable property of global object.

the code works in browser because "default scope" global scope. var bar therefore declares global variable, becomes property of global object.

however in node, every file considered module. each module has own scope. in case,var bar not create global variable, module scoped variable. since there no global variable bar, this.bar undefined.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -