Question 1:
What's the different between Code A and Code B?
Code A:
var obj = {length:0};
var push = Array.prototype.push;
push.call(obj,'1st value')
push.call(obj,'2nd value');
Code B:
Array.prototype.slice(arguments,0)
Answer:
First off, Code B is wrong and should be the following.
Code B2:
function test(){
var args = Array.prototype.slice.call(arguments,0);
return args;
}
Unless defined, arguments exist within the scope of a function. Basically arguments is an object literal with the initial state of {length:0}.
When a function is called with an argument, the argument is stored in the object arguments by the index corresponding to the argument position.
Example:
function getFirstArgument(){
return arguments[0];
}
console.log( getFirstArgument(1,2,3) === 1 );
The purpose of Code B2 is to convert the arguments object into an array so you can get access to the array prototype functions easily.
Example:
// returns the arguments as an array in reverse order.
function reverseArguments(){
return Array.prototype.slice.call(arguments).reverse();
}
console.log( reverseArguments(1,2,3).join(",") === "3,2,1" );
So as you can see, both obj in Code A and arguments in Code B are the same object initially.
However, Code A is adding values to obj, while Code B2 is converting arguments to an array.
More information here:
What's the use of array.prototype.slice.call(arguments,0)
MDN Array.slice
Question 2:
Will "Code A" work in major browsers?
Answer:
Most likely. However, if you want to guarantee that it works, then rewrite the push fuction.
var push = function( obj, val ){
if( typeof obj !== "object" ){
return;
}
obj.length = obj.length || 0;
obj[ obj.length ] = val;
return ++obj.length;
};
Usage:
var obj = {};
console.log( push( obj, 1 ) === 1 );
console.log( push( obj, 1 ) === 2 );
console.log( JSON.stringify( obj ) === "{"0":1,"1":1,"length":2}" );