Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Kjetil-Lennart A. Lorentzen
Kjetil-Lennart A. Lorentzen
13,390 Points

A question about 'this' and best practice.

I am just starting out with JavaScript, i started programming here in February, i started with the Front-End development track. I've spent a lot of time reading, watching videos and making my own codes to make sure everything sticks, and that i'm "ahead" of my courses.

Now, that you have my background, these are my questions:

I watched a talk given by Douglas Crockford, it was at JSConfUY 2014 and he called it "the better parts", which is also a book he wrote. (it's on youtube, it was pretty funny and informative. Also very high-level, i didn't understand it all.)

Anyway, i'm learning "this" in the object oriented javascriptcourse now, and Douglas says he stopped using "this", and that it's because of security, if i understood him right.

Should we even use this? And how is it a security-risk? and should we be worried?

I've read a lot, and i come across "we shouldn't use <method>, we should use <other method> as it is more secure" a lot. I have a hard time understanding these statements.

What should i keep in mind when it comes to security and javascript?

1 Answer

Steven Parker
Steven Parker
231,275 Points

Douglas Crockford is an extremely knowledgeable, and opinionated, guy. He doesn't always agree with the majority of other people who influence the development of the language, so keep that in mind. But that said, I will occasionally take his side instead of the majority's.

But I'd particularly recommend caution involving advice (his or other's) where you don't completely understand the basis. The concerns he describes as "security" related might not apply at all to what you are working on.

But security aside, usage of "this" can cause code to be more complicated than necessary and lead to errors. Like most things in programming, you should always consider your options and select the one most suited to the task. Often there are alternatives that make the code more clear and robust, such as passing in the event object to handlers instead of relying on "this" to access the target element.