In a browser this
will be interpreted as the window object in this case and the variable str
will be defined on the window. There is no window object in Node. It's not clear why you are using this
at all here rather than using regular scoping rules. This will work in both the browser and Node:
var str = "hello"
function printStr(){
console.log(str); // will see outside scope
}
printStr();
Better yet, pass the value into the function so it doesn't depend on values defined outside its scope:
var str = "hello"
function printStr(s){
console.log(s);
}
printStr(str);
In Node there is a global
object, which has some similarity to the browser's window
object so code like this can work in Node, but it would be a fairly non-standard way to do this:
global.str = "hello"
function printStr(){
console.log(this.str)
}
printStr();