Answering Nicholas Zakas' JavaScript quiz
A current meme that's floating around the JavaScript geek corner of the internet is setting quizzes
We have a simple JavaScript class:
We create a new User:
All is well. Unless we forgot the 'new':
Curses! That's not what we want at all. By omitting the 'new' keyword, the JavaScript engine executes our 'User' constructor in the current scope, which in this case is the global window object. With the scope ('this') set to window, setting 'this.name' is now the same as setting 'window.name', which is not what we're trying to do.
Here's the problem though, omitting the 'new' keyword is still perfectly valid syntax. We know at design time if 'new' must be used or not, and can use a little trick to make it act as though 'new' was indeed used:
Because the 'new' keyword sets up a new context, we can just test to see if 'this' is now an instance of our class. If it's not, it means the user has omitted the 'new' keyword, so we do it for them. John Resig has an example of this over on his blog.
This is all very well and good, but I don't think we should use it. The reason is that we're hiding a pseudo syntax error from the developer, instead of educating them with its correct usage. If we hide this mistake in each class we write, our unknowing developer will remain unknowing, and run into a wall when they repeat their mistake on classes that don't fix it for them.
Instead, I suggest the following:
The only difference of course is that we're throwing an Error instead of fixing the developer's mistake. The benefit is that their syntax won't actually work unless they write it correctly. This is good because our erstwhile developer is prompted to fix their code and understand why it was wrong. Better informed developers leads to better code.
Well, hopefully.
If you're interested in exploring more about JavaScript's intricacies, consider reading Answering Nicholas Zakas' JavaScript quiz, which delves into the quirks and nuances of the language. Additionally, the article on Ext.override - Monkey Patching Ext JS offers insights into extending JavaScript libraries, highlighting both the potential and risks of such techniques.
A current meme that's floating around the JavaScript geek corner of the internet is setting quizzes
In JavaScript we have at least 4 ways of defining functions: [code lang='js'] function myFunction()
The Module Pattern is a way of using a closure in JavaScript to create private variables and functio
Writing a library is a balancing act between the (sometimes competing) interests of API clarity, cod