Javascript/Gotchas

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

Object Methods Aren't Bound

Unlike Python, obj.func doesn't return a bound function. That is, the following code will surprise you:

var f = obj.func;
f();

See, obj.func doesn't get called with this set to obj. Instead, it is set to window, which is usually what you didn't expect.

In order to work around this, remember to bind it manually.

The Javascript way:

var f = function () { obj.func(); };
f();

The MochiKit way:

var f = bind(obj.func, obj);

HTML Encoding Doesn't Work in Strings

Let's say you want to embed a special character -- © -- in a Javascript string.

Since you are developing HTML side-by-side with Javascript, you are probably going to try this:

"©"

But that won't work the way you expect. See, the string "©" is literally & - c - o - p - y - ; -- six letters.

The way you have to do it is first look up the character code in hex. For instance, here is a good page. Note that the copyright symbol is A9. So you escape that with \x in the string.

"\xA9"

If it is 4 hex digits, then you would escape it with \u

"\u00A9"