0
function setFoo(input){
    this.foo = input;
}

var foo = 5;
console.log('foo in global : '+foo);  // => 5 

var obj = {
    foo : 10
}

console.log('foo in obj: '+obj.foo); // => 10
setFoo(20);

// Point
console.log('foo in global '+foo); // => js : 20, node.js : 5


// JavaScript Result : 5, 10, 20
// Node.js Result : 5, 10, 5

Hello, I'm learning Node.js, I want to enhance my code so I bought javascript book and reading it, there is something that I couldn't tell exactly why the results are different in JavaScript and Node.js.

Can you tell me why?

I think It is related with 'Context' concept. I thought this.foo in Javascript refers to window.foo. and in Node.js, firstly I thought it is global.foo and I expected same result, but it's not. What is this.foo in Node.js and what is proper way to show same result?

Thanks.

ton1
  • 7,238
  • 18
  • 71
  • 126

0 Answers0