r/javascript • • Feb 21 '18

I am A JavaScript instructor at Microsoft. AMA.

Hi r/javascript!

My name is Benjamin Lin. I am a content developer at Microsoft and teach courses on JavaScript and JavaScript frameworks at Microsoft. You can see my Top 10 JavaScript Questions course here.

I can help answer tips & tricks on learning JavaScript, questions about Microsoft, and all things tech.

AMA!

Proof.

Edit: about 15 minutes left!

More edit: Thanks everyone for visiting me at this AMA! I really enjoyed getting the chance to interact with the JavaScript community and hear your honest thoughts. It was worth waking up early today to do this =)

if you have any more questions, feel free to hit me up on twitter @benjlin or follow me on instagram @bens_jams

540 Upvotes

257 comments sorted by

View all comments

Show parent comments

3

u/kuenx Feb 22 '18

That's grossly oversimplified and will get you in trouble sooner or later.

1

u/Ob101010 Feb 22 '18

I agree. Can you come up with a good ELI5 analogy?

2

u/kuenx Feb 22 '18 edited Feb 22 '18

I think the above explanation is so simple that it's wrong half the time. If you really make this your "what is this" mental bridge you'll write a lot of broken code and you won't understand why. And you won't understand or misinterpret a lot of other people's code.
ELI5 are supposed to explain something in a simple way. They can maybe be incomplete but they shouldn't be wrong. Writing them is hard sometimes.

'the object to the left of the dot operator' is just the object that has a property that holds your function. It does not give you an indication of what this inside your function will be. To find that out you have to go look at how the function is defined.

const Bananas = { count: 10 };
const Apples = { count: 5 };

Apples.bar = function () { console.log(this); }.bind(Bananas);
Apples.foo = () => console.log(this);
const bar = Apples.bar;

Apples.foo() // Apples is 'the thing to the left of the dot' and therefore 'this'
// Well, no. The `this` inside `Apples.foo` is the global object (the `window` in browsers).

bar() //window is 'the thing to the left of the dot'
// Well, no. The  `this` inside `bar` is `Bananas`.

this is the execution context of your function and it points to what ever value is bound to it, either manually or automatically. And it can change depending on how you call your function. That may not be good enough for a 5 year-old though.