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.

0

u/[deleted] May 28 '19

[deleted]

→ More replies (3)

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.

1

u/PalestineFacts May 29 '19 edited May 29 '19

Add in a console.log(a); at the very end and you'll see what's going on.

console.log(a) will print out 2 meanwhile console.log(this.a) will be printing out 1.

Also notice what happens if you were to explicitly declare a reference to the context.

let app = this;

this.a = 1;

and then within the function write:

app.a = 2;

console.log(app.a);

and then outside of the function type:

console.log(this.a);

Now both values print out with the value 2. The answer is not so obvious I guess. Your guess would have been correct if the last console.log() in the original poster's example was console.log(a) instead of console.log(this.a);

→ More replies (2)

1

u/calligraphic-io May 28 '19

That's what I would expect, and also what I get running the code in Node.

16

u/tchaffee May 28 '19

It's not complicated. People simply don't take the time to learn. Which is a shame, because it takes about an hour to learn. Here are the rules in the words of Kyle Simpson:

Determining the this binding for an executing function requires finding the direct call-site of that function. Once examined, four rules can be applied to the call-site, in this order of precedence:

  1. Called with new? Use the newly constructed object.

  2. Called with call or apply (or bind)? Use the specified object.

  3. Called with a context object owning the call? Use that context object.

  4. Default: undefined in strict mode, global object otherwise.

Instead of the four standard binding rules, ES6 arrow-functions use lexical scoping for this binding, which means they adopt the this binding (whatever it is) from its enclosing function call. They are essentially a syntactic replacement of self = this in pre-ES6 coding.

That's not complicated. Take the hour or so to read the two chapters on this from the You Don't Know JS series, and you'll be good.

7

u/senocular May 28 '19

Sure, some basic rules make it seem easy, but what rule is this?

button.addEventListener('click', owner.func)

3? No, but most beginners would think so, and not without reason. When it comes to callbacks the waters are murky, and that's where 99% of issues with this come from.

8

u/tchaffee May 28 '19

I guess that could be confusing, but that's not the call site. How long does it take to learn that? I have yet to see someone still be confused about this after taking the time to learn the actual rules and then apply those rules to analyzing code in their daily work. In almost every case of confusion, the person does not know the rules at all. Fair point that beginners could be confused because they don't know all the rules yet. But if something takes an hour to learn, I don't think "beginner" is much of an excuse. Just spend the hour.

4

u/senocular May 28 '19

Yes, but once they learn all the rules of the language, they're no longer a beginner ;)

2

u/tchaffee May 28 '19

That doesn't have much with the point I'm trying to make which is specifically that it's not complicated, which is what parent comment claims. I agree that it's something beginners don't know.

4

u/DerGernTod May 28 '19

well, in that case the function call-site is no longer owner, but rather button. the owner object doesn't have anything to do with this function call anymore. for those cases i'd rather do something like that: button.addEventListener('click', (e) => owner.func(e)) which (probably) has the desired behaviour. or, if you don't want to use an additional function, it get's a bit messy: button.addEventListener('click', owner.func.bind(owner))

2

u/[deleted] May 28 '19

Indeed. I have been doing js for 5+ years and still sometimes have head scratching moments with this.

1

u/robolab-io May 28 '19

clone masterrace reporting in

1

u/Dangle76 May 28 '19

Isn’t it the same thing as “self” in python?

1

u/mcvoid1 May 28 '19

The short answer: it doesn't.

→ More replies (7)