John Resig - Bug Fixes in JavaScript 2
arguments is now a 'real array'
arguments is now a 'real array', as opposed to an array-like object, with the following distinctions:
arguments.toString()
behaves like an object's .toString()
, rather than an array's.- If you manipulate the
.length
property its contents aren't deleted (if the length is reduced), nor are new items added (if the length is increased).
This means that you can now do simple things like:
arguments.slice(1);
Whereas, previously, you would have to do:
Array.prototype.slice.call( arguments, 1 );
this
propagationIf you now define a function inside another, its
this
is bound to the
this
of the outer function, as opposed to the global object (e.g. window).
This makes the following code possible:
function User(name){
this.name = name;
function test(){
alert(this.name);
}
test();
}
Whereas, previously, you would've had to have used a closure to store a reference to this and retrieve it within
test()
. The resulting code would have looked something like this:
function User(name){
var self = this;
this.name = name;
function test(){
alert(self.name);
}
test();
}
Trailing CommasWhen initialising an object, trailing commas are ignored (some implementations already support this).
var obj = {
a: 1,
b: 2,
};
It's now being made expressly clear that a trailing comma in an array initialisation does not create an extra undefined entry at the end of the array. JScript currently gets this implementation detail wrong, even though it was specified in ECMAScript 3. The correct result is as follows:
[a, b,].length
>> 2 (not 3)
Single-Character SubstringsYou can now get single characters out of a string by using
[index]
, instead of the
.charAt(index)
method. This way was already widely implemented.
'string'[0]
>> 's'
for .. in orderWhen looping through the properties of an object the order in which they were returned was left up to the implementation - now it's required that the properties be returned in the order in which they were created. The final result would allow for the following, intuitive, result:
var obj = {1: 2, p: 'hi', '_':'under'};
for ( var i in obj )
alert(i);
>> alert('1')
>> alert('p')
>> alert('_')