You-dont-know-js: this & object prototypes - chapter 2 - example code seems wrong

Created on 30 Sep 2017  Â·  12Comments  Â·  Source: getify/You-Dont-Know-JS

When I run the code below:
function foo() { console.log(this.a); } var a = 2; foo(); // 2
I get "undefined" in my console but the book says it should print 2.
Where is the problem?

Most helpful comment

CommonJS wraps .js files in a boilerplate function. See https://nodejs.org/api/modules.html#modules_the_module_wrapper

All 12 comments

I dunno... works for me:

screen shot 2017-09-30 at 7 09 56 am

Weird! When I run this code in chrome's web console it gives me the correct output but when I run it with nodejs compiler then I get "undefined" instead of 2!

Node's "global scope" is not a purely standard JS environment and cannot be trusted to give you accurate JS behavior like this.

CommonJS wraps .js files in a boilerplate function. See https://nodejs.org/api/modules.html#modules_the_module_wrapper

I didn't know that. Thanks guys!

@bmeck on that topic, I've always wondered why Node has to do that for the main .js file it's executing, as opposed to only doing it for any modules you load?

@getify to inject things like require (scoped to file path and not a global) and module (process.mainModule === module) for people to use. Also prevents various differences like allowing top level return depending on how a module is loaded.

Node is also deciding to register this file type as a separate MIME : https://github.com/nodejs/TSC/issues/371

@bmeck doesn't node care that their deviations confuse JS devs? :)

IIRC the v8 API provides a way to inject identifiers into scope without having to wrap code in an IIFE, no?

@getify doesn't have files be wrapped/not wrapped depending on how they are loaded just add to the confusion?

it should be noted that injecting variables isn't sufficient, grammar/this value also changes

grammar/this should never have been changed, that's my point, it perpetually confuses developers, like in this thread.

That ship has long since passed and I was just explaining things.

On Sep 30, 2017 10:39 PM, "Kyle Simpson" notifications@github.com wrote:

grammar/this should never have been changed, that's my point, it
perpetually confuses developers, like in this thread.

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/getify/You-Dont-Know-JS/issues/1156#issuecomment-333351074,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAOUowyqwtBNjfkXtGu0WajAYvO97t2Rks5snwl1gaJpZM4PphB1
.

Was this page helpful?
0 / 5 - 0 ratings