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

5

u/[deleted] Feb 21 '18

I actually think "this" has a built in real world analogy: The word "this".

"This" derives it's entire meaning from context. Saying "This is good." without context doesn't mean anything. However, if you are eating pasta and saying "This is good", you are referring to the pasta. At least, that's the metaphor that keeps it straight in my head :D

However, the asynchronicity of Javascript is something that I continuously have to keep in mind when I'm designing a solution. I have to start thinking of things as reactions to events as opposed to the next step in a procedure. That can be mind breaking if you have any other programming experience.

1

u/Ob101010 Feb 21 '18

If only it were that simple...

function foo() {
    console.log(this)
}

myObj = {}
myObj.f = foo.bind(myObj)

myOtherObj = {}
myObj.f.call(myOtherObj)

myOtherObj.wack = () => new Function('x','x()')(foo)
myOtherObj.wack.call(myObj) //lost track of this yet?

Use your analogy to get me to the line with '//lost track of this yet?'

3

u/[deleted] Feb 21 '18

I mean, sure. This is a confusing example. Doing weird things with code will always result in code that is difficult to explain to someone new to Javascript. If this was presented to a Javascript noob as a teaching too, I'd question that teacher's methods. I also don't know that completely understanding this example is useful for someone new to JS. But if the goal is to demonstrate that "this" can be super weird and have it's meaning super obscured, then mission successful.

It has been my experience that relating "this" to the English definition of "this" gets you pretty far though.

-1

u/Ob101010 Feb 21 '18

See, thats the thing here : the answer stares you in the face, and this is quite a simple puzzle. It depends on you knowing an arcane tidbit (I love these) : the new Function has this set to window, no matter the context.

While contrived, Im 100% sure that this kind of thing is used in some useful way somewhere in javascript.

With async, you can get out of callback hell a number of ways, and explain async easily to a noob.

Not so with this.