ffff
ffff

Reputation: 3070

Javascript closure not working as expected

I'm running this code on nodejs. I was wondering why the closure when executed does not print the string 'Globals'? Isn't the this in the closure pointing to the global scope?

// Running on NodeJS, not in a browser!
this.name = "Globals";

function Person(name) {
  this.name = name;
  this.namePrinter = function() {
    return function() {
      console.log(this.name);
    }
  }
}

var p = new Person("Faiz");
p.namePrinter()(); // prints undefined. Shouldn't it print Globals?
console.log(this.name); // prints Globals

Upvotes: 3

Views: 127

Answers (1)

georg
georg

Reputation: 214959

Your example works as intended in a browser, but in node.js this on the top level is not the same as global, it's your module .exports. So when you do

this.name = "Globals";

It assigns name: Globals to module.exports, not to the global object.

Now, when you write

p.namePrinter()();

it's the same as:

func = p.namePrinter();
func();

The function is unbound (= there's no object. before it), so its this will be the global object. But there's no name there...

In browsers, your top level code is executed in the context of the global object (which is window) and this is the same object unbound functions use. That's why your snippet works.

Upvotes: 5

Related Questions