r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

61

u/[deleted] May 28 '19

[removed] — view removed comment

28

u/[deleted] May 28 '19

more importantly, understanding the different contexts of this:

this in the global space => window

this in a function => function context

this in a method of an object => the object

this with call/apply/bind => whatever you want it to be

edit for ES6: this is not bound in arrow functions, so the value bound outside the arrow function will be found and used instead.

5

u/[deleted] May 28 '19

[removed] — view removed comment

7

u/[deleted] May 28 '19

I would guess 2 for the inner log, and 1 for the outer log. Am I mistaken?

5

u/[deleted] May 28 '19

[removed] — view removed comment

5

u/[deleted] May 28 '19

What’s the answer, and what’s the context of this that I missed? I’d like to add it to the list above.

5

u/DerGernTod May 28 '19

if i'd guess: the IIFE is invoked from the current scope, so basically it's similar to assign it to a property on this and then call the property, e.g. this.b = function() { ... }; this.b(). the function is only defined in the context of this, so i guess that's why it takes that context. to find out the answer without spoiling it to others, just run the code :D

4

u/senocular May 28 '19

Not exactly. Scope doesn't really come into play for context (value of this) except for arrow functions where this is specifically taken from the scope.

Here, you have a function that is called as a normal function and not from an object as an object method. Even though its an IIFE, it operates just as it would as if you named it and called if from a single variable name. Given that it's not called from an object, the function will use the default binding which sets this as the global object (or undefined in strict mode).

In this example, we have to assume we're not in strict mode since it would error if we were. So we're running the code in global which makes this.a = 1 set a global variable. Then when called, the function's context is also global, so it sets the same global property, a, to 2. Then all logs that follow log that same a.

But you could have just as well called this same function in some other function where this in that scope was different and this function would still have a global context.