What "Hidden Features" of JavaScript do you think every programmer should know?
After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript.
- Hidden Features of HTML
- Hidden Features of CSS
- Hidden Features of PHP
- Hidden Features of ASP.NET
- Hidden Features of C#
- Hidden Features of Java
- Hidden Features of Python
Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.
You can also extend (inherit) classes and override properties/methods using the prototype chain spoon16 alluded to.
In the following example we create a class Pet and define some properties. We also override the .toString() method inherited from Object.
After this we create a Dog class which extends Pet and overrides the .toString() method again changing it's behavior (polymorphism). In addition we add some other properties to the child class.
After this we check the inheritance chain to show off that Dog is still of type Dog, of type Pet, and of type Object.
Both answers to this question were codes modified from a great MSDN article by Ray Djajadinata.
Methods (or functions) can be called on object that are not of the type they were designed to work with. This is great to call native (fast) methods on custom objects.
This code crashes because
listNodes
is not anArray
This code works because
listNodes
defines enough array-like properties (length, [] operator) to be used bysort()
.Off the top of my head...
Functions
arguments.callee refers to the function that hosts the "arguments" variable, so it can be used to recurse anonymous functions:
That's useful if you want to do something like this:
Objects
An interesting thing about object members: they can have any string as their names:
Strings
String.split can take regular expressions as parameters:
String.replace can take a regular expression as a search parameter and a function as a replacement parameter:
You may catch exceptions depending on their type. Quoted from MDC:
NOTE: Conditional catch clauses are a Netscape (and hence Mozilla/Firefox) extension that is not part of the ECMAScript specification and hence cannot be relied upon except on particular browsers.
You can use the in operator to check if a key exists in an object:
If you find the object literals too ugly you can combine it with the parameterless function tip:
You don't need to define any parameters for a function. You can just use the function's
arguments
array-like object.