<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title>arv-o-matic</title>
	<subtitle>The Weblog of Erik Arvidsson</subtitle>
	<link href="http://erik.eae.net/atom.xml" rel="self" />
	<link href="http://erik.eae.net/" />
	<updated>2014-09-01T17:21:39Z</updated>
	<id>http://erik.eae.net/</id>
	<author>
		<name>Erik Arvidsson</name>
	</author>
	<generator>Eleventy</generator>

	<entry>
		<title>Traceur on JavaScript Jabber</title>
		<link href="http://erik.eae.net/archives/2014/09/01/09.21.39/" />
		<updated>2014-09-01T17:21:39Z</updated>
		<published>2014-09-01T17:21:39Z</published>
		<id>http://erik.eae.net/archives/2014/09/01/09.21.39/</id>
		<category term="JavaScript" />
		
		<content type="html"><![CDATA[<p><img src="http://google.github.io/traceur-compiler/logo/tc.svg" style="width:150px;border:0" class="alignleft" /></p>
<p>Last week the interview with me on <a href="http://javascriptjabber.com/123-jsj-traceur-with-erik-arvidsson/">JavaScript Jabber went live</a>. The interview is a about <a href="https://github.com/google/traceur-compiler">Traceur</a> but we also ended up talking quite a bit about ES6.</p>
]]></content>
	</entry>

	<entry>
		<title>JavaScript: Muddy Waters of Reflection</title>
		<link href="http://erik.eae.net/archives/2013/02/24/12.59.21/" />
		<updated>2013-02-24T20:59:21Z</updated>
		<published>2013-02-24T20:59:21Z</published>
		<id>http://erik.eae.net/archives/2013/02/24/12.59.21/</id>
		<category term="JavaScript" />
		<category term="ES6" />
		
		<content type="html"><![CDATA[<p>Just like a lot of other people I have a love-hate relationship with JavaScript. I love how expressive it is and I love that it runs everywhere but there are also some things where the languages falls very short.</p>
<p>The gripe of the day is how JS makes reflection part of the everyday programming flow. And it is not reliable reflection, it is crippled reflection with lots of gotchas. I&#8217;ll focus on two reflection mechanisms in JS today, for-in loops and square bracket annotations (member lookup expression, <code>array['length']</code>). The foor-in loop is used to loop over the properties of an object. But it only includes enumerable properties. Also, it incudes the enumerable properties of the objects prototype. The member lookup expression is used to lookup a property based on its name, which is always a string.</p>
<p>The problem is that people tend to use this reflective mechanism to do Map data structures. It is not surprising since there is no Map data structure in JS (before ES6) and the syntax is very convenient. Of course you want to write what you mean; <code>map[key] = value</code> instead of <code>map.set(key, value)</code>.</p>
<p>Lets go on. What if I want to add a <code>size</code> getter on my map that returns the number of entries in the map? Now I can no longer add an entry with the key <code>"size"</code> since that would replace or shadow the <code>size</code> getter. This is a real problem and a lot of web site crash if you enter the string <code>"__proto__"</code> or the string <code>"hasOwnProperty</code>. For example Google Docs used to crash if you entered the former of those two.</p>
<p>What if I wanted to have non string keys? Nope, only strings are allowed and the key will be the <code>toString()</code> string of the key object. The common solution to this is to build a Map data structure where the key is a unique ID (UID) and the UID gets added to the real key object. This of course breaks if the key is a non extensible objects and those of you who have been around for a long time might remember that Nodes coming from an XHR in IE where non extensible causing all kinds of head aches.</p>
<h2>The Future</h2>
<p>ES6 has a new kind of loop called for-of. The for of loop is not a reflective loop. It is an iteration loop. The object that you want to iterate over must have an iterator and by default <code>Object.prototype</code> does not. <code>Array.prototype</code> on the other hand has an iterator that iterates over the elements in the array. Just what you always wanted!</p>
<pre><code>for (let value of [0, 'one', true]) {
  console.log(value);
}

for (let value of {a: 1}) {  <span style="color: red">// throws not iterable</span>
  console.log(value);
}
</code></pre>
<p>ES6 has Map and Set which allows any value as a key. This solves some of the issues but we still have the mess with the member lookup expression.</p>
<p>There is a <a href="http://wiki.ecmascript.org/doku.php?id=strawman:object_model_reformation">proposal on the ES wiki</a> that tries to reform the object model and decouple <code>[]</code> from property lookup. The basic idea is that any object can override the <code>[]</code> operations. Existing objects would continue to work as they do today but new objects could opt in to this new behavior.</p>
<p>For example, we could extend the ES6 Map objects to allow <code>[]</code> and <code>[]=</code> like this:</p>
<pre><code>import {elementGet, elementSet} from '@name';
Map.prototype[elementSet] = function(key, value) {
  return this.set(key, value);
};
Map.prototype[elementGet] = function(key) {
  return this.get(key);
};

var m = new Map;
var key = {};
m[key] = 42;
console.log(m[key]);
</code></pre>
<p>The reformed object model also allows us to finally explain how arrays work. It also allows us to implement all of the DOM interfaces in pure JavaScript. For example we could implement NodeList like this:</p>
<pre><code>import {create, elementGet} from '@name';
const ownerName = create();
const lengthName = create();

export function NodeList(owner) {
  this[ownerName] = owner;
}

NodeList.prototype  = {
  get length() {
    let i = 0;
    for (let node = this[ownerName].firstChild; node; node = node.nextSibling) {
      i++;
    }
    return i;
  },

  [elementGet]: function(index) {
    let i = 0;
    for (let node = this[ownerName].firstChild; node; node = node.nextSibling) {
      if (i++ === index)
        return node;
    }
    return node;
  }
};
</code></pre>
<h2>Today</h2>
<p>Map and Set are implemented in SpiderMonkey and V8 and is available under a <a href="http://erik.eae.net/archives/2011/12/29/00.00.29/" title="JavaScript Harmony in Chrome">flag in Chrome</a> and in Firefox without a flag.</p>
<p>For-of loops are available in Firefox. V8 hasn&#8217;t started working on for-of loops nor iterators so don&#8217;t expect to be able to use these without a transpiler any time soon.</p>
<p>Both for-of loops and the reformed object model are available in the <a href="http://code.google.com/p/traceur-compiler/">Traceur</a> compiler. There is a naïve <a href="http://traceur-compiler.googlecode.com/git/example/collection.html">demo</a> of a string keyed map too. Note that [] keys are not yet supported in object/class literals so the demo uses assignment instead.</p>
]]></content>
	</entry>

	<entry>
		<title>Iterating over Harmony Maps</title>
		<link href="http://erik.eae.net/archives/2012/02/05/13.40.34/" />
		<updated>2012-02-05T21:40:34Z</updated>
		<published>2012-02-05T21:40:34Z</published>
		<id>http://erik.eae.net/archives/2012/02/05/13.40.34/</id>
		<category term="JavaScript" />
		
		<content type="html"><![CDATA[<p>A while ago Chrome <a href="http://erik.eae.net/archives/2011/12/29/00.00.29/" title="JavaScript Harmony in Chrome">got</a> some JavaScript Harmony features (behind a flag). One of these features is the new <a href="http://erik.eae.net/archives/2011/12/29/12.00.11/" title="Harmony Collections">Map</a> &#8220;class&#8221;. The current implementation does not provide a way to iterate over the keys or values because that depends on <a href="http://wiki.ecmascript.org/doku.php?id=harmony:iterators">Harmony iterators</a> which are not yet implemented in V8.</p>
<p>However, we can create our own class that adds support for iteration. I&#8217;ve uploaded a <a href="https://github.com/arv/for-each-map">simple implementation</a> to GitHub.</p>
<p>The implementation creates a new &#8220;class&#8221; since V8 does not correctly allow sub classing of <code>Map</code>. The name of this &#8220;class&#8221; is <code>ForEachMap</code> since it provides one additional method over the standard <code>Map</code>, a <code>forEach</code> method. The <code>forEach</code> method calls a function for every key-value pair in the map.</p>
<p>Usage:</p>
<pre><code>var map = new ForEachMap;
map.set('a', 'A');
map.set('b', 'B');
map.forEach(function(value, key) {
  console.log(key, value); 
});
</code></pre>
<p>The iteration order is the same as the key-value pair creation order. Changes to the map is allowed during iteration and deleted keys are guaranteed to not be visited and new keys will be visited in the current iteration.</p>
<p>The implementation uses a <code>WeakMap</code> as a side table for the private state of the map. The private state contains arrays with keys and values and a real <code>Map</code> that maps the key to the given index. It also keeps track of number of holes in these arrays so that we can reindex the arrays when there are too many holes.</p>
<p>This wrapper is of course unfortunate but at least it makes the <code>Map</code> &#8220;class&#8221; more useful while we wait for implementations to add support for native iteration.</p>
]]></content>
	</entry>

	<entry>
		<title>Proxies</title>
		<link href="http://erik.eae.net/archives/2011/12/31/00.00.01/" />
		<updated>2011-12-31T08:00:01Z</updated>
		<published>2011-12-31T08:00:01Z</published>
		<id>http://erik.eae.net/archives/2011/12/31/00.00.01/</id>
		<category term="JavaScript" />
		<category term="Chrome" />
		
		<content type="html"><![CDATA[<p>V8 currently implements the same <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy">Proxy API as Firefox</a>. The API for proxies has <a href="http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies">changed a bit</a> since then so be extra careful when testing this.</p>
<p>Proxies are a very low lever construct. The are very powerful and they allow an object to intercept any access to its properties as well as intercept things like <code>[[Call]]</code> and <code>[[Construct]]</code>. There are some limitations though; the <code>[[Prototype]]</code> cannot change once created and there is currently no way to intercept internal properties such as <code>[[Class]]</code>.</p>
<p>The basic idea is that you create a new object (the proxy) that has a handler. The handler has a bunch of functions that will get called when different operations are done to the proxy object. For example when someone sets a property the <code>set</code> set trap of the proxy is called.</p>
<pre><code>var handler = {
  set: function(receiver, name, value) {
    console.log(name, 'was set to', value, 'on', receiver);
  }
};
var proxy = Proxy.create(handler, {});
proxy.meaning = 42;  // Logs 'meaning' was set to 42 on [Object object]
</code></pre>
<p>Proxies are useful to emulate DOM as well as for doing membranes etc. I don&#8217;t expect anyone but library authors to ever have to use them directly.</p>
]]></content>
	</entry>

	<entry>
		<title>typeof null</title>
		<link href="http://erik.eae.net/archives/2011/12/30/12.00.40/" />
		<updated>2011-12-30T20:00:40Z</updated>
		<published>2011-12-30T20:00:40Z</published>
		<id>http://erik.eae.net/archives/2011/12/30/12.00.40/</id>
		<category term="JavaScript" />
		<category term="Chrome" />
		
		<content type="html"><![CDATA[<p>In ES5 <code>typeof null</code> evaluates to <code>'object'</code>. This quirk was one of the changes we wanted to fix in ES5 but at the time we agreed that we did not want any semantic changes. With Harmony there will be a way to opt in (TBD) so when you opt in we can now provide a better value for <code>typeof null</code>.</p>
<pre><code>
typeof null  // 'null'
</code></pre>
<p>In V8 with the Harmony flag turned on this changes all the <a href="http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null"><code>typeof</code></a> expressions so beware and please update your JS libraries to be future compatible to handle this correctly. Something along the following lines should make your code work both in ES5 and in future versions of ES:</p>
<pre><code>
switch (typeof expression) {
  case 'boolean':
    ...
    break;
  case 'function':
    ...
    break;
  case 'number':
    ...
    break;
  case 'string':
    ...
    break;
  case 'undefined':
    ...
    break;
  default:  // object or null
    var isNull = expression === null;
    ...
}

// Bad, because it included null in old ES versions
typeof object === 'object'

// Good
object === null
</code></pre>
<p><!--</p>
<p>http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null</p>
<p>--></p>
]]></content>
	</entry>

	<entry>
		<title>Block Scope</title>
		<link href="http://erik.eae.net/archives/2011/12/30/00.00.27/" />
		<updated>2011-12-30T08:00:27Z</updated>
		<published>2011-12-30T08:00:27Z</published>
		<id>http://erik.eae.net/archives/2011/12/30/00.00.27/</id>
		<category term="JavaScript" />
		<category term="Chrome" />
		
		<content type="html"><![CDATA[<p>Did you know that ES5.1 does not support function declarations inside blocks? Browsers do allow it but they do not agree on the semantics. For ES Harmony we are specifying the semantics for <a hre="http://wiki.ecmascript.org/doku.php?id=harmony:block_functions">functions inside blocks</a>. Functions inside block use <code>let</code> scope, which means that they are limited to the current block scope.</p>
<pre><code>function f() { console.log('outer'); }

{
  function f() { console.log('inner'); }
  f();  // logs 'inner'
}
f();  // logs 'outer'
</code></pre>
<p>The <a href="http://wiki.ecmascript.org/doku.php?id=harmony:block_scoped_bindings">block scoped bindings</a> proposal also covers <a href="http://wiki.ecmascript.org/doku.php?id=harmony:let%3Cbr%20/%3E"><code>let</code></a> and <a href="http://wiki.ecmascript.org/doku.php?id=harmony:const%3Cbr%20/%3E"><code>const</code></a>. The <code>let</code> binding is like a <code>var</code> except that its scope is limited to the current block. <code>const</code> is like let but it requires an initializer and can only be written to once.</p>
<pre><code>var functions = [];
for (var i = 0; i &lt; 5; i++) {
  var x = i;
  functions.push(function() {
    alert(x);
  });
}
functions[0]();
</code></pre>
<p>The code above alerts <code>5</code> because that is what x is when the function is called. Now lets change the inner <code>var</code> to a <code>let</code>.</p>
<pre><code>var functions = [];
for (var i = 0; i &lt; 5; i++) {
  let x = i;
  functions.push(function() {
    alert(x);
  });
}
functions[0]();
</code></pre>
<p>This now alerts <code>0</code> since every iteration gets a fresh local variable.</p>
<pre><code>const PI = 3.14159265;
// ...
PI = 'Apple Pie';  // throws because PI cannot be reassigned to.
</code></pre>
<p><!--</p>
<p>http://wiki.ecmascript.org/doku.php?id=harmony:block_scoped_bindings</p>
<p>http://wiki.ecmascript.org/doku.php?id=harmony:let</p>
<p>http://wiki.ecmascript.org/doku.php?id=harmony:const</p>
<p>http://wiki.ecmascript.org/doku.php?id=harmony:block_functions</p>
<p>--></p>
<p>To use these you currently need to use strict mode.</p>
<pre><code>'use strict';
// ...

// or
function f() {
  'use strict';
  // ...
}
</code></pre>
]]></content>
	</entry>

	<entry>
		<title>Harmony Collections</title>
		<link href="http://erik.eae.net/archives/2011/12/29/12.00.11/" />
		<updated>2011-12-29T20:00:11Z</updated>
		<published>2011-12-29T20:00:11Z</published>
		<id>http://erik.eae.net/archives/2011/12/29/12.00.11/</id>
		<category term="JavaScript" />
		<category term="Chrome" />
		
		<content type="html"><![CDATA[<p>Simple maps and sets allow you to create a <a href="http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets%3Cbr%20/%3E">Map</a> with an object as the key. Normally people use <code>Object.create(null)</code> as a map but that limits the keys to strings. The <a href="http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets%3Cbr%20/%3E">Set</a> constructor is similar and it allows a set containing objects. Neither of these currently support a way of iteration since iteration is planned to be covered by the <a href="http://wiki.ecmascript.org/doku.php?id=harmony:iterators">iteration</a> proposal which is not yet implemented.</p>
<pre><code>var map = new Map;
map.set('a', 'A');
map.get('a');  // 'A'
var b = {};
map.set(b, 'B');
map.get(b);  // 'B'
map.has(b);  // true
</code></pre>
<pre><code>var set = new Set;
set.add('a');
set.has('a');  // true
var b = {};
set.add(b);
set.has(b);  // true
</code></pre>
<p>Harmony also provides another kind of map called <code>WeakMap</code>. This has the same API as <code>Map</code> but it has different GC semantics. A normal <code>Map</code> using an object as a key prevents the object from being garbage collected but with a <code>WeakMap</code> the object can be garbaged collected. This is useful when you associate data with someone else&#8217;s object.</p>
<pre><code>var map = new WeakMap;
map.set(elementA, 'A');
map.get(elementA);  // 'A'
map.set(elementB, 'B');
map.get(elementB);  // 'B'
map.has(elementB);  // true
</code></pre>
<p>In the above example, if the element is removed from the DOM and the script has no references to it the element can be garbage collected.</p>
<p>Unlike <code>Map</code> and <code>Set</code>, <code>WeakMap</code> will never have a way to iterate over the items since that would expose the GC behavior.</p>
<p><!--</p>
<p>http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets</p>
<p>http://wiki.ecmascript.org/doku.php?id=harmony:weak_maps</p>
<p>--></p>
]]></content>
	</entry>

	<entry>
		<title>JavaScript Harmony in Chrome</title>
		<link href="http://erik.eae.net/archives/2011/12/29/00.00.29/" />
		<updated>2011-12-29T08:00:29Z</updated>
		<published>2011-12-29T08:00:29Z</published>
		<id>http://erik.eae.net/archives/2011/12/29/00.00.29/</id>
		<category term="JavaScript" />
		<category term="Chrome" />
		
		<content type="html"><![CDATA[<p>We recently added a way to turn on JavaScript Harmony features in Chrome. If you have a <a href="http://www.chromium.org/getting-involved/dev-channel">Canary</a> or a recent <a href="http://www.chromium.org/getting-involved/dev-channel">Developer Channel</a> build of Chrome you can turn on some Harmony features from <code>chrome://flags</code>. You need to manually enter that address in your browser. Look for an entry called &#8220;Enable Experimental JavaScript&#8221;</p>
<p>The following 4 features are currently enabled if you turn on the experiment.</p>
<ul>
<li><a href="http://erik.eae.net/archives/2011/12/29/12.00.11/">Collections (<code>Map</code>, <code>Set</code>, <code>WeakMap</code>)</a>
</li><li><a href="http://erik.eae.net/archives/2011/12/30/00.00.27/">Block scoped bindings</a>
</li><li><a href="http://erik.eae.net/archives/2011/12/30/12.00.40/"><code>typeof null === 'null'</code></a>
</li><li><a href="http://erik.eae.net/archives/2011/12/31/00.00.01/">Proxies</a>
</li></ul>
<p>Over the next couple days I&#8217;ll post individual posts about each of these.</p>
]]></content>
	</entry>

	<entry>
		<title>Adding transformation passes to Traceur Compiler</title>
		<link href="http://erik.eae.net/archives/2011/09/16/21.52.24/" />
		<updated>2011-09-17T05:52:24Z</updated>
		<published>2011-09-17T05:52:24Z</published>
		<id>http://erik.eae.net/archives/2011/09/16/21.52.24/</id>
		<category term="Uncategorized" />
		
		<content type="html"><![CDATA[<p>Traceur Compiler is an open source ES.next to ES5 compiler. We released it a while back but today I finished writing a tutorial about how to add new <a href="http://code.google.com/p/traceur-compiler/wiki/AddingTransformationPasses">transformation passes</a>. As you can see it is pretty easy to add new passes and all you need to know is JavaScript to prototype the future of JavaScript now.</p>
]]></content>
	</entry>

	<entry>
		<title>Inheritance Antipattern</title>
		<link href="http://erik.eae.net/archives/2009/11/09/21.12.16/" />
		<updated>2009-11-10T05:12:16Z</updated>
		<published>2009-11-10T05:12:16Z</published>
		<id>http://erik.eae.net/archives/2009/11/09/21.12.16/</id>
		<category term="Uncategorized" />
		<category term="JavaScript" />
		
		<content type="html"><![CDATA[<p><a href="http://blog.bolinfest.com/">Michael Bolin</a> wrote an excellent blog post about the <a href="http://blog.bolinfest.com/2009/11/closure-compiler-turns-pattern-into.html">inheritance antipattern</a> that is gaining a lot of foothold among JavaScript developers these days. The post also links to <a href="http://bolinfest.com/javascript/inheritance.php">an article</a> giving a lot more depth on the topic.</p>
<blockquote cite="http://blog.bolinfest.com/2009/11/closure-compiler-turns-pattern-into.html"><p>
When I attended The Ajax Experience 2009, I saw a number of &#8220;misguided&#8221; things that people were doing with JavaScript. [snip].. I wanted to get up and yell, &#8220;Stop &#8212; you&#8217;re all doing it wrong!&#8221;
</p></blockquote>
<p>Although I agree with almost everything Michael writes I think it is worth pointing out some things.</p>
<h3>Background</h3>
<p>For those too lazy to read Michael&#8217;s post and article here is an example of the classic inheritance pattern as well as the functional inheritance pattern. This example is intentionally very simple.</p>
<h4>Classic inheritance pattern</h4>
<pre>
function Phone(phoneNumber) {
  this.phoneNumber_ = phoneNumber;
};

Phone.prototype.getPhoneNumber = function() {
  return this.phoneNumber_;
};
</pre>
<h4>Functional inheritance pattern</h4>
<pre>
function Phone(phoneNumber) {
  var that = {};
  that.getPhoneNumber = function() {
    return phoneNumber;
  };
  return that;
};
</pre>
<h3>Compilation</h3>
<p>Michael argues that the functional pattern is not good because methods cannot be inlined and the end result is much larger. He also says that it uses more memory. I think it is important to realize that it uses a LOT more memory and is significantly slower. Given a <i>class</i> with 1 methods It is about 100 times slower in Chrome, 20 times slower in Safari and about 10 times slower in Firefox.</p>
<h3>Prototype object literal</h3>
<p>Michael also mentions the following pattern:</p>
<pre>
function Phone(phoneNumber) {
  this.phoneNumber_ = phoneNumber;
}
Phone.prototype = {
  getPhoneNumber: function() {
    return this.phoneNumber_;
  }
};
</pre>
<p>I like this pattern but it has one serious drawback. It cannot be used to extend existing <i>classes</i> because in that case the protytype must be an instance of the <i>class</i> you are inheriting from.</p>
<p>If you do not care about IE support this can be done by using <code>__proto__</code> like this:</p>
<pre>
function SmartPhone(phoneNumber) {
  Phone.call(this, phoneNumber);
}
SmartPhone.prototype = {
  <b>__proto__: Phone.prototype,</b>
  sendEmail: function(email) {
    ...
  }
};
</pre>
<h3>Semantics</h3>
<p>I understand why people like Douglas Crockford preaches the functional inheritance pattern. Due to its closure the local variable is truly private and this is important when you are doing mashups and other security sensitive code. However, when it comes to building large scale applications like Gmail you cannot afford this extra memory and performance overhead.</p>
<h3>Conclusion</h3>
<p>Prototype based inheritance is the way to go if you care about memory usage and performance. If you are planning to use the <a href="http://code.google.com/closure/compiler/">Closure Compiler</a> you will also see greater code size reduction using this pattern.</p>
<h3>Update</h3>
<p>As some people pointed out method dispatch is slightly slower using the classic inheritance pattern because we have to walk the prototype chain to find the method. I&#8217;m also posting my tests and results for reference:</p>
<ul>
<li><a href="https://dl.dropbox.com/u/182043/inheritance-perf.html">Create test</a></li>
<li><a href="https://dl.dropbox.com/u/182043/inheritance-call-perf.html">Method dispatch test</a></li>
<li><a href="http://spreadsheets.google.com/pub?key=tNL6gDY557Bb4aQjSb6rQ9g&#038;output=html">Table of results</a></li>
</ul>
<p>You might need to reduce the number of runs to get this to wrok in IE. The only surprising thing here is that the classical pattern is faster in Firefox nightlies.</p>
]]></content>
	</entry>

	<entry>
		<title>Closure</title>
		<link href="http://erik.eae.net/archives/2009/11/05/22.27.29/" />
		<updated>2009-11-06T06:27:29Z</updated>
		<published>2009-11-06T06:27:29Z</published>
		<id>http://erik.eae.net/archives/2009/11/05/22.27.29/</id>
		<category term="Uncategorized" />
		<category term="Google" />
		<category term="JavaScript" />
		
		<content type="html"><![CDATA[<p>Today we finally announced and released Closure (or Closure Library as the JS library is officially known as).</p>
<h3>History</h3>
<p>Me and <a href="http://pupius.co.uk/blog/">Dan Pupius</a> started the JS library at Google a long time ago. At the time there was a lot of good JS code at Google but there was really no order to it and the code was spread out all over the code base. This of course made it hard to discover which in turn lead to the same code being reimplemented over and over. As you might guess the code that existed was not very consistent and sometimes did not even work in the presence of other code. Closure was an attempt to bring a <a href="http://en.wikipedia.org/wiki/Closure_(psychology)">closure</a> to this mess. The name is also a play on the <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">programming language feature</a> as well as the desire to make our js library be a <a href="http://en.wikipedia.org/wiki/Transitive_closure">closure</a> of all the existing js code at Google.</p>
<p>At the time we were considering using <a href="http://www.dojotoolkit.org/">Dojo</a> as our base for this new library. We were very impressed with Dojo but back then Dojo was too unstable and we had heard too many horror stories of upgrade migration head aches. We also looked at <a href="http://mochikit.com/">MochiKit</a> which was more stable but it did not really solve any of our problems. (<a href="http://erik.eae.net/archives/2009/11/05/22.27.29/third_party">*</a>)</p>
<h3>Today</h3>
<p>We have had more than 400 Google engineer contributing code to Closure. The code is constantly evolving but I feel like it has stabilized a lot over the last year or so. It is used by almost all of Google&#8217;s web applications and the amount of QA and usage these apps have is unheard of for any web application.</p>
<p>I&#8217;m very happy that <a href="http://www.nanaze.com/">Nathan</a> and <a href="http://www.ginnotvodka.com/">Daniel</a> took upon themselves to release this because neither me nor Dan has had the bandwidth to do it.</p>
<h3>Future</h3>
<p>I hope we can see more code being shared among the different open source JS libraries out there. We would love to be able to <code>goog.require</code> some Dojo code (especially their data model code) and I&#8217;m sure they would love to be able to <code>dojo.require</code> our data structures and i18n code.</p>
<h3>Closure Compiler</h3>
<p>Closure relies heavily on the <a href="http://code.google.com/closure/compiler/">Closure Compiler</a> to concatenate files, doing static type analysis, as well as code optimizations such as inlining and dead code removal. Closure Library is great for prototyping but it gets slow real fast due to all the network request that are done at startup as well as downloading all the code that you do not really need. The compiler solves both these problems.</p>
<h4 id="third_party">Third Party Code</h4>
<p>We ended up using both Dojo (we use Acme for <a href="http://code.google.com/p/closure-library/source/browse/trunk/third_party/closure/goog/dojo/dom/query.js">goog.dom.query</a>) and we use MochiKit&#8217;s Deferred in <a href="http://code.google.com/p/closure-library/source/browse/trunk/third_party/closure/goog/mochikit/async/deferred.js">goog.async.Deferred</a>.</p>
]]></content>
	</entry>

	<entry>
		<title>EcmaScript Edition 5 is final</title>
		<link href="http://erik.eae.net/archives/2009/04/09/16.58.54/" />
		<updated>2009-04-10T00:58:54Z</updated>
		<published>2009-04-10T00:58:54Z</published>
		<id>http://erik.eae.net/archives/2009/04/09/16.58.54/</id>
		<category term="JavaScript" />
		
		<content type="html"><![CDATA[<p>After a lot of back and forth in the TC and the failure of ES4 the TC was focused on ES3.1. The final spec for ES3.1 is now called <a href="http://www.ecma-international.org/news/PressReleases/PR_Ecma_finalises_major_revision_of_ECMAScript.htm">EcmaScript, Fifth Edition</a>.</p>
<p>The most exciting thing in ES5 is that it finally standardize getters and setters. It also allows us to control the enumerability as well as whether properties should be read only etc. ES5 also adds a few other things like the array extras from Mozilla.</p>
]]></content>
	</entry>

	<entry>
		<title>New Explorer Canvas Release</title>
		<link href="http://erik.eae.net/archives/2009/03/22/14.02.31/" />
		<updated>2009-03-22T22:02:31Z</updated>
		<published>2009-03-22T22:02:31Z</published>
		<id>http://erik.eae.net/archives/2009/03/22/14.02.31/</id>
		<category term="Uncategorized" />
		<category term="ExplorerCanvas" />
		<category term="Google" />
		<category term="HTML5" />
		<category term="Internet Explorer" />
		<category term="JavaScript" />
		<category term="Open Source" />
		
		<content type="html"><![CDATA[<p>Over at the newly created <a href="http://explorercanvas.blogspot.com/">Explorer Canvas Blog</a> we announced the new release.</p>
]]></content>
	</entry>

	<entry>
		<title>Playing around with WebKit Animations</title>
		<link href="http://erik.eae.net/archives/2009/02/20/17.47.41/" />
		<updated>2009-02-21T01:47:41Z</updated>
		<published>2009-02-21T01:47:41Z</published>
		<id>http://erik.eae.net/archives/2009/02/20/17.47.41/</id>
		<category term="Uncategorized" />
		<category term="animaton" />
		<category term="css" />
		<category term="Transition" />
		<category term="WebKit" />
		
		<content type="html"><![CDATA[<p>Ever since WebKit started to introduce <a href="http://webkit.org/specs/">all these fancy new CSS properties like 2D and 3D transformations, transitions and declarative animations</a> I&#8217;ve been drooling like a script kiddie from the year 2000. I&#8217;ve been thinking about how I can use them in some Google property but unfortunately the whole world is not using nightly builds of WebKit so I&#8217;m pretty limited to just playing around at home. Well, platying around home is not<br />
exactly what I did. Most of the time I was actually playing on the bus going home from work.</p>
<p>I&#8217;ve been playing around doing a KeyNote like animation done with CSS and some JS to hook up the necessary events. The animation is kind of like a deck of cards. When you go to the next one the current one zooms in and fades out,<br />
symbolizing getting closer to the viewer. The next card then zooms and fades in from the back and to give a fancy effect <img src="http://erik.eae.net/wp-includes/images/smilies/icon_wink.gif" alt=";-)" class="wp-smiley" /> </p>
<h2>V1</h2>
<p><a href="http://erik.eae.net/playground/webkit/animation1.html">Example 1</a> (use left and right arrow keys to go between the cards.</p>
<p>I started off playing around with the @keyframes rule. This is the CSS animation that gives you most control and it should be good enough to be able to replace most of your js animations. I believe JS libraries should be able to use the CSS animation internally as long as no code depends on &#8221; any animation&#8221; events except start and begin.</p>
<p>The CSS animation allows you to set the animation-name at the time you want to start your animation. You can set up multiple keypoints at different intervals but for the simplest case you only need to set the from (0%) and to (100%) frames.</p>
<p>For the animation I had in mind I needed 4 animations. fade-in-backwards, fade-out-backwards, fade-in-forwards and fade-out-forwards. These are extremely simple and I was very tempted to create these using the CSSOM but I never went that far.</p>
<p>To play the animation forward I set the animation-name of the current card to fade-out-forward and the next card to fade-in-forward (and the fade-*-backward for animation backwards).</p>
<p>The CSS animations has a few drawbacks. One of them is that when the animation is finished it is pretty cumbersome to freeze the state. One way to achieve the freezing is to listen to the window.onwebkitanimationend event , check the<br />
animationName of the event, read the computed style and apply that. The problem with this is that I either iterate over all CSS properties used in the to (100%) keyframe or I manually keep track of the properties I want to freeze. I ended up<br />
manually setting the properties because I was laze. This does not scale well of course so if you are serious about freezing your animations I would recommend writing functions to freeze the animation (you will need to be able to unfreeze<br />
it if you want to animate it again).</p>
<p>I can think of two other drawbacks. One is mentioned in the spec proposal and that is the ability to pause the animation. The spec proposal currently supports this but they are considering removing it. If they remove it the user will have to write some non trivial js to freeze the state again (same thing as I talked about before). I&#8217;m not even sure how resuming would work since I don&#8217;t think there is a way to set the time for the animation.</p>
<h2>V2</h2>
<p><a href="http://erik.eae.net/playground/webkit/animation2.html">Example 2</a></p>
<p>It turned out that my use case is actually a transition (surprise) and for transitions, CSS transitions are much better suited.</p>
<p>Transitions allow you to change a CSS property (any property that supports transitions) and it will animate the property when changed. For example, if you say that &#8220;width&#8221; should be a transition-property, setting the width will animate the width from its old width to the new width. I cannot emphezise enough how useful this property is. Please reread this paragraph and makes sure you get it <img src="http://erik.eae.net/wp-includes/images/smilies/icon_smile.gif" alt=":-)" class="wp-smiley" />  Now how many lines of js do you need to make your elements fade in and out when you show and hide them? None, it is easily done with one line of CSS (if<br />
you use opacity to hide them that is).</p>
<p>So back to the KeyNote like demo. The idea here is to set all the coming cards to zoomed out and totally transparent and all the previous cards to zoomed in and transparent. Now you only need to change which element is current by setting the zoom to 100% and the opacity to 1. Done!</p>
<p>That is not entirely true, I also updated the class name of the previous and next card.</p>
<h2>V3</h2>
<p><a href="http://erik.eae.net/playground/webkit/animation3.html">Example 3</a></p>
<p>This is an iteration on the previous one. Instead of defining .next, .current and .previous classes I realized I could use the :target CSS selector in combination with the next sibling selector. The :target selector matches any<br />
element with the same id as the hash fragment of the URL. This is mostly used for highlighing the target of an internal anchor that was clicked but it can be used for other more fancy things (like tab panes for example).</p>
<p>When the page loads I needed to ensure that the URL contained a hash fragment and if it didn&#8217;t I replaced the URL with one that did. Also, I needed to add some code to sync the current card with the hash, allowing the user to bookmark<br />
the correct card. A feature that should be part of any sane web app.</p>
<h2>Conclusion</h2>
<p>I cannot wait till we can use things like this in all browsers. It will surely make the web a richer experience. Once again, I&#8217;d like to thank the WebKit team for a totally excellent web browser and for pushing the web foward. I don&#8217;t know<br />
what I would do without you <img src="http://erik.eae.net/wp-includes/images/smilies/icon_smile.gif" alt=":-)" class="wp-smiley" /> </p>
]]></content>
	</entry>

	<entry>
		<title>Offline Gmail</title>
		<link href="http://erik.eae.net/archives/2009/02/03/22.06.38/" />
		<updated>2009-02-04T06:06:38Z</updated>
		<published>2009-02-04T06:06:38Z</published>
		<id>http://erik.eae.net/archives/2009/02/03/22.06.38/</id>
		<category term="Google" />
		<category term="Gears" />
		<category term="Gmail" />
		<category term="Offline" />
		
		<content type="html"><![CDATA[<p>Last week we launched <a href="http://gmailblog.blogspot.com/2009/01/new-in-labs-offline-gmail.html">Offline Gmail</a>. After releasing <a href="http://gears.google.com/">Gears</a> I moved to the Gmail team to work on Offline Gmail. I think it was pretty obvious that we were working on this and Offline Gmail was the first and possibly the hardest task we wanted to be able to solve with Gears.</p>
<p>A lot of things have been said about Offline Gmail but not too much has been said about how it was implemented. If there is any interest I&#8217;ll take questions and answer those in a follow up blog post.</p>
<p>One thing that I would like to add is that even though the UI for enabling the offline lab is only available in English you can still get Offline Gmail in any language Gmail supports. Here is how:</p>
<ol>
<li>Change your language to English</li>
<li>Go to Labs and enable the Offline lab.</li>
<li>Switch back to your language of choice.</li>
<li>Enable offline from the offline settings tab or from the link next to your user name in the upper right corner.</li>
</ol>
]]></content>
	</entry>

	<entry>
		<title>Using catch-alls to implement super in SpiderMonkey</title>
		<link href="http://erik.eae.net/archives/2008/11/27/12.54.49/" />
		<updated>2008-11-27T20:54:49Z</updated>
		<published>2008-11-27T20:54:49Z</published>
		<id>http://erik.eae.net/archives/2008/11/27/12.54.49/</id>
		<category term="JavaScript" />
		<category term="Mozilla" />
		
		<content type="html"><![CDATA[<p>Another thing that always been bothering me about OOP in JS is that calling super is such a pain.  Some libraries do ugly hacks like checking the source (by calling <code>toString</code> on their constructor and method function objects) and then wrap the original function in another function that encapsulates a variable called super. Other libraries do even worse things like rewriting the code of the function and eval&#8217;ing it. These hacks work in most cases (not in Opera for mobile phones) but it is very inefficient.</p>
<p>Yesterday morning (when reading a lengthy email to es-discuss) I realized that I could probably use catch-alls to emulate super. Catch-alls is a SpiderMonkey feature that allows an object to have a method that will be called when a non existing method is called.  Catch-alls are proposed for ES-Harmony. The idea I had was to create a super object that uses the catch-all mechanism to call the method on the super <em>class</em> with this bound to the current object. I wanted to achieve something like this:</p>
<pre><code>function B() {
  supr(1, 2, 3);
  this.method = function(x) {
    supr.method(x);
    ...
  };
}
inherits(B, A);</code></pre>
<p>Instead of having to write:</p>
<pre><code>function B() {
  A.call(this, 1, 2, 3);
  this.method = function(x) {
    A.prototype.method.call(this, x);
    ...
  };
}
inherits(B, A);</code></pre>
<p>So <code>supr</code> needs to be a function which has the <code>__noSuchMethod__</code> method set to call the method of the <code>[[Prototype]]</code> object.</p>
<p>Take one:</p>
<pre><code>function B() {
  var self = this;
  var supr = function() {
    return A.apply(self, arguments);
  };
  supr.__noSuchMehod__ = function(name, args) {
    return A.prototype[name].apply(self, args);
  };

  supr(1, 2, 3);
  this.method = function(x) {
    supr.method(x);
    ...
  };
}
inherits(B, A);</code></pre>
<p>Lets take a look at the inherits function. It is something all js dev heads should have in their repertoire.  It is extremely useful and it allows you to declare inheritance without having to create an instance of the super class.</p>
<pre>function inherits(child, parent) {
  var f = function() {};
  f.prototype = parent.prototype;
  child.prototype = new f;
  child.prototype.constructor = child;
  child.superClass = parent;
}</pre>
<p>The last two lines are important because JS does not maintain the mapping to the <code>constructor</code> and by adding the <code>superClass</code> property it allows us to easily get access to the parent constructor.</p>
<p>With the innards of the <code>inherits</code> function known combined with take one above we can write a helper function that makes creating the supr object a lot easier.</p>
<pre><code>function createSuper(self, opt_constr) {
  var constr = opt_constr || arguments.callee.caller;
  function supr() {
    return constr.superClass.apply(self, arguments);
  };
  supr.__noSuchMethod__ = function(name, args) {
    if (typeof constr.superClass.prototype[name] == 'function') {
      return constr.superClass.prototype[name].apply(self, args);
    }
    throw Error('No such method, ' + name);
  };
  return supr;
}</code></pre>
<p>And then we can use this.</p>
<pre><code>function A(x) {
  print('In A constructor, x = ' + x);
}
A.prototype.a = function(x) {
  print('In A.prototype.a, x = ' + x);
};


function B(x) {
  print('In B constructor');
  var supr = createSuper(this);

  supr(x || 'From B');
  var className = 'B';
  this.a = function(x) {
    print('In ' + className + '.a');
    supr.a(1);
  };
}
inherits(B, A);


function C(x) {
  print('In C constructor');
  var supr = createSuper(this);

  supr(x || 'From C');
}
inherits(C, B);
C.prototype.a = function() {
  var supr = createSuper(this, C);
  print('In ' + 'C' + '.a');
  supr.a('supr.a called from a c object');
};


print('Creating an instance of B');
b = new B;
b.a(2);

print('');
print('Creating an instance of C');
c = new C;
c.a();</code></pre>
<p><a href="http://erik.eae.net/playground/super.html">Try this</a> (Firefox only)</p>
<p>This works because <code>supr</code> is recreated for every constructor and is bound lexically Don&#8217;t do <code>this.supr = supr</code> and think you can reuse it. It will not work. This does not require that you put the methods that needs super inside the constructor but if you don&#8217;t you will have to call <code>createSuper</code> and pass in your constructor from your method which is not very efficient and it is hardly much better than using the straight forward way to call super by just getting the function of the super class prototype and call it by name (<code>A.prototype.a.call(this, 1)</code>).</p>
<h3>Conclusion</h3>
<p>Once again I find that adding code to make things simpler in JS is unsuccessful. The costs for adding better ways to do things don&#8217;t pay for itself. (Except for the inherits function of course.)</p>
]]></content>
	</entry>

	<entry>
		<title>Instance private, class private, package and friends</title>
		<link href="http://erik.eae.net/archives/2008/11/14/23.47.04/" />
		<updated>2008-11-15T07:47:04Z</updated>
		<published>2008-11-15T07:47:04Z</published>
		<id>http://erik.eae.net/archives/2008/11/14/23.47.04/</id>
		<category term="JavaScript" />
		
		<content type="html"><![CDATA[<p>Update: This is flawed. See details at the end.</p>
<p>This post was inspired by a&nbsp;<a href="http://www.robertnyman.com/2008/10/29/javascript-namespacing-an-alternative-to-javascript-inheritance/">post</a> that Robert Nyman wrote a while back. At the same time I was thinking about how to achieve private fields without the memory issues.</p>
<p>JavaScript does not have private members as understood by a lot of other object oriented programming languages. However it can use closures to achieve the same effect. Below is a very typical code sample.</p>
<pre><code>function Cartman() {
  var secret = 'Tea party';
  this.guessSecret = function(guess) {
    return guess == secret;
  };
}</code></pre>
<p>This is pretty straight forward and works because we define the public method in the scope of the local variable which now works like a private property. There are a pros and cons with this pattern:</p>
<p>Pros: Simple and easy to understand.</p>
<p>Cons: Very memory hungry since every instance needs its own function to encapsulate the local vars.</p>
<p>Therefore most libraries that are object heavy uses a naming convention for private fields. The most common convention is to prefix the field with an underscore.</p>
<pre><code>function Cartman() {
  this._secret = 'Tea party';
}

Cartman.prototype.guessSecret = function(guess) {
  return guess == this._secret;
};</code></pre>
<p>Now all instances can share the methods but we lost the integrity. Anyone can read <code>_secret</code> of an instance.</p>
<p>I&#8217;ve been playing around with hybrid models that allows methods to be shared but still allow real private members.</p>
<p>My first idea was to use a closure outside the actual constructor and define a key there. Then basically store the private state in an object that is guarded by that key. This turns out to change the model from instance private to class private. This means that all instances of a class can access the private state of all other instances of that class. Some OOP do this intentionally. Java does this for example.</p>
<p>The code for this quickly gets ugly but below is a working example.</p>
<pre><code>// Define variable outside anonymous block. Will be set inside the block.
var A;
(function() {
  var KEY = {};

  /**
   * Helper function to get the private state object.
   * @param {!Object} obj The object to get the private state for.
   * @return {!Object} The private state object.
   */
  function getPrivate(obj) {
    return obj._getPrivateWithKey(KEY);
  }
  
  /**
   * Store the private state object in a closure.
   * @param {!Object} obj The object
   * @param {!Object} state The state.
   */
  function setPrivate(obj, state) {
    // Add a convenience method.
    obj._getPrivateWithKey = function(key) {
      if (key === KEY) {
        return state;
      }
      throw Error('Permission denied');
    };
  }

  // Set the external variable here.
  A = function (a) {
    var P = {
      a: a
    };
    setPrivate(this, P);
  };

  A.prototype.getA = function() {
    return getPrivate(this).a;
  };
})();</code></pre>
<p><a href="http://erik.eae.net/playground/private2.html">Try it</a>.</p>
<p>This works because the object is associated with the key inside <code>setPrivate</code> using a closure. The function <code>getPrivate</code> which uses the <code>KEY</code> is only visible inside the anonymous function scope and therefore only code inside the anonymous function can get access to the private state.</p>
<p>This actually leads to any code inside the anonymous function being able to see the private state of an object. You can therefore use this concept to allow different classes defined within the same anonymous function scope to see each others private state. This can be treated as a sealed package &#8212; a package that cannot be reopened after it has been closed.</p>
<p>We can take this concept one step further and add support for C++ style friends by giving away our key to someone else. Something like:</p>
<pre><code>var A;
(function() {
  var KEY = {};
  A = ...;

  var friendKeys = {};
  A.addFriend = function(id, key) {
    friendKeys[id] = key;
  };

  function getFriendPrivate(obj, id) {
    return obj._getPrivateWithKey(friendKeys[id]);
  }

  A.prototype.accessFriendPrivate = function(obj) {
    return getFriendPrivate(obj).b;
  };
})();

var B;
(function() {
  var KEY = {};
  B = ...;
  A.addFriend('B', KEY);
})();</code></pre>
<p><a href="http://erik.eae.net/playground/friend.html">Try it</a>.</p>
<p>Now instances of A can access the private state of instances of B.</p>
<h3>Conclusion</h3>
<p>Is this really useful? I would say no. It adds too much boiler plate code without enough real gain. A lot of people try to apply known concepts from languages like Java and apply them to JavaScript. If you really need to be able to hide the state then I would use the instance private pattern first used in this post. It is easy to write and easy to understand and does not have a lot of boiler plate code. However, I would only use it where hiding the state really matters. In most cases it doesn&#8217;t. For example, Gmail was written without any true private members. We just use a naming convention.</p>
<p>This also brings up a related topic which is using JS as an object capability language and Doug Crockford made an <a href="http://www.slideshare.net/webdirections/douglas-crockford-ajax-security-presentation">excellent presentation</a> about this a while back.</p>
<h3>Update</h3>
<p>henrah pointed out that this model is flawed since the key leaks. Anyone can override <code>_getPrivateWithKey</code> to get access to the key.</p>
]]></content>
	</entry>

	<entry>
		<title>Just Married</title>
		<link href="http://erik.eae.net/archives/2008/10/12/12.12.03/" />
		<updated>2008-10-12T20:12:03Z</updated>
		<published>2008-10-12T20:12:03Z</published>
		<id>http://erik.eae.net/archives/2008/10/12/12.12.03/</id>
		<category term="Personal" />
		
		<content type="html"><![CDATA[<p><img src="http://erik.eae.net/wp-content/uploads/2008/10/toi-sin-erik.jpg" alt="Toi Sin &amp; Erik, October 4th 2008" width="480" height="720" class="alignnone size-full wp-image-223" /></p>
<p>Photo by our friend Stella Loh.</p>
]]></content>
	</entry>

	<entry>
		<title>Google Chrome</title>
		<link href="http://erik.eae.net/archives/2008/09/02/22.06.22/" />
		<updated>2008-09-03T06:06:22Z</updated>
		<published>2008-09-03T06:06:22Z</published>
		<id>http://erik.eae.net/archives/2008/09/02/22.06.22/</id>
		<category term="Friends" />
		<category term="Google" />
		<category term="Software" />
		<category term="Web" />
		<category term="WebKit" />
		
		<content type="html"><![CDATA[<p>I guess you all have downloaded <a href="http://www.google.com/chrome/">Chrome</a> already.  If not, what are you waiting for?</p>
<p>I&#8217;d like to congratulate my friends who have been working so hard on this.  Congratulations <a href="http://glenmurphy.com/blog/2008/09/google-chrome.html">Glen</a> and Ojan.</p>
<p>Also, I&#8217;d like to add that Chrome is totally awesome, and I&#8217;m not saying that because I work at Google.  I&#8217;m saying that because it is the simple truth <img src="http://erik.eae.net/wp-includes/images/smilies/icon_wink.gif" alt=";-)" class="wp-smiley" /> </p>
]]></content>
	</entry>

	<entry>
		<title>IE8 and box-sizing</title>
		<link href="http://erik.eae.net/archives/2008/03/10/21.48.10/" />
		<updated>2008-03-11T05:48:10Z</updated>
		<published>2008-03-11T05:48:10Z</published>
		<id>http://erik.eae.net/archives/2008/03/10/21.48.10/</id>
		<category term="DHTML" />
		<category term="Internet Explorer" />
		<category term="JavaScript" />
		<category term="Microsoft" />
		
		<content type="html"><![CDATA[<p>One of my top feature request for IE8 was for it to support <a href="http://www.w3.org/TR/css3-ui/#box-sizing">box-sizing</a>.  I&#8217;m happy to see that <a href="http://msdn2.microsoft.com/en-us/library/cc196965(VS.85).aspx">IE8 does support <code>box-sizing</code></a> although it has a annoying quirk.  The DOM property name is not correct.  The rule for translating CSS property names to DOM property names is to replace a dash followed by a character by the uppercase character. Using JavaScript it can be written like this:</p>
<pre><code>function toCamelCase(s) {
  return s.replace(/\-(\w)/g, function(_, c) {
    return c.toUpperCase();
  });
}</code></pre>
<p>Since the CSS property for <code>box-sizing</code> in IE8 is <code>-ms-box-sizing</code> the DOM property name <del datetime="2008-03-11T15:18:38+00:00">is</del> <ins datetime="2008-03-11T15:18:38+00:00">should be</ins> <code>MsBoxSizing</code>. The <code>-ms-</code> prefix is a defacto standard for non standard CSS properties and Firefox, WebKit and Opera has tons of <code>-moz-</code>, <code>-webkit-</code> and <code>-o-</code> respectively.</p>
<p>We would therefore have to add a browser check in our function above:</p>
<pre><code>function toCamelCase(s) {
  return s.replace(/\-(\w)/g, function(_, c, i) {
    if (MSIE &#038;&#038; i == 0) {
      return c;
    }
    return c.toUpperCase();
  });
}</code></pre>
<p>Not only does this require more code it also adds a mental obstacle and one more quirk to add to the already overflowing quirk-filled brains of developers world wide.</p>
]]></content>
	</entry>

</feed>
