API Prototype

Page 35

Chapter

3 Array Prototype extends all native Javascript arrays with quite a few powerful methods. This is done in two ways: •

It mixes in the Enumerable module, which brings a ton of methods in already.

It adds quite a few extra methods, which are documented in this section.

With Prototype, arrays become much, much more than the trivial objects we were used to manipulate, limiting ourselves to using their length property and their [] indexing operator. They become very powerful objects, that greatly simplify the code for 99% of the common use cases involving them.

Why you should stop using for…in to iterate (or never take it up) Many JavaScript authors have been misled into using the for…in JavaScript construct to loop over array elements. This kind of code just won’t work with Prototype. 1

You see, the ECMA 262 standard, which defines ECMAScript 3rd edition, supposedly implemented by all major browsers including MSIE, defines numerous methods on Array (§15.4.4), including such nice methods as concat, join, pop and push, to name but a few among the ten methods specified. This same standard explicitely defines that the for…in construct (§12.6.4) exists to enumerate the properties of the object appearing on the right side of the in keyword. Only properties specifically marked as non-enumerable are ignored by such a loop. By default, the prototype and the length properties are so marked, which prevents you from enumerating over array methods when using for…in. This comfort led developers to use for…in as a shortcut for indexing loops, when it is not its actual purpose.

1

http://www.ecma-international.org/publications/standards/Ecma-262.htm


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.