Bob5421
Bob5421

Reputation: 9073

nodejs difference between global and this

I do not understand the difference between this and global in node js. It looks like to be the same thing to my eyes.

Let's have a look in the nodejs interpreter:

> this.toString()
'[object global]'

Okay so i suppose this is the same thing than global when we are in the global scope. Let's do the same thing in a function. (i have also tried a subfunction)

> f3= function f1() { function f2() { console.log(this.toString()); } f2(); };
[Function: f1]
> f3()
[object global]

As you can see here this is global too.

Can anyone tell me when this is not the same thing than global ?

Thanks

Upvotes: 0

Views: 144

Answers (1)

Felix Kling
Felix Kling

Reputation: 816374

Can anyone tell me when this is not the same thing than global ?

In Node specifically:

  • Inside a module this refers to exports

In JavaScript in general:

  • When a function is invoked in such as way that this is set implicitly or explicitly:
    • Called via .call/.apply (explicit)
    • As a method (foo.bar()) (implicit)
    • As constructor (new Foo()) (implicit)
    • The called function is strict (this will be undefined)
  • When a function's this was explicitly bound to another value (via .bind)

There are only two cases where this refers to the global object:

  • this in global scope
  • A non-strict, unbound function is called the "normal" way: foo().

See also How does the "this" keyword work?

Upvotes: 2

Related Questions