zacurry
zacurry

Reputation: 906

difference between function context (this) in node.js and browser

I am aware of how "this" works in a browser context , and how its value changes in different scenarios like when using arrow functions how the function is invoked.

I printed out "this" in different scenarios for node js (express js, to be more specific), and it is containing a lot more data - including path names etc

My question is :
1. are the rules concerning 'this' exactly the same for node.js ?
2. could any one explain the node.js 'this' object properties or point me to a simple article.

Thank you!

Upvotes: 0

Views: 215

Answers (3)

Tom
Tom

Reputation: 6709

I observed a difference between this in a module when running on node (tests) and a browser (production).

in tests:

the following type of code worked fine when run by tests:

export function A()
{
}

export function B()
{
  // NOTE: DON'T DO THIS. prepending "this." is not needed and might break.
  this.A();
}

But on production it would throw:

TypeError: Cannot read property 'A' of undefined

However this is NOT a difference between node + browser/webview but rather a difference between production code (production build of bundle.js via webpack v4) and code running in tests.

With a debug build of bundle.js this would point to the module (so an object containing exported module symbols) eg:

{
  A : [Function: A]
  B : [Function: B]
}

Whereas in a release build of bundle.js this returns undefined

This difference of behaviour is caused by webpacks concatenateModules optimization.

Upvotes: 1

ralphtheninja
ralphtheninja

Reputation: 133008

This this object is whatever the global object is in that context. In node that is the process object.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707258

There are no different rules for this in a browser vs. node.js. The rules are set by the ECMAScript standards and both the browser's Javascript implementation and the one in node.js follow the same ECMAScript standards.

What you are probably looking at is a "default" value for this in some particular context. In a browser, you are probably looking at a default value for this that may be the window object. In node.js, if you see filenames, you may be looking at a module handle as the default value for this or the global object.

To help you more specifically, we would need to see the code around where you were examining the value of this in each environment and also know whether you were running in strict mode or not.

In most cases, this is not used with just a default value, but rather a specific object that the this value is set to. For example, if you are calling something like:

obj.method();

Then, inside the implementation of method, the Javascript interpreter will set the value of this to obj. This is a part of the object oriented nature of Javascript.

Upvotes: 2

Related Questions