Reputation: 9073
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
Reputation: 816374
Can anyone tell me when this is not the same thing than global ?
In Node specifically:
this
refers to exports
In JavaScript in general:
this
is set implicitly or explicitly:
.call
/.apply
(explicit)foo.bar()
) (implicit)new Foo()
) (implicit)this
will be undefined
)this
was explicitly bound to another value (via .bind
)There are only two cases where this
refers to the global object:
this
in global scopefoo()
.See also How does the "this" keyword work?
Upvotes: 2