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.

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);