Reputation: 328
Kindly I am a beginner in JavaScript world, and I have a question with the below simple example,
function myFun(){
return arguments;
}
var myVar=myFun("a","b","c");
//1
console.log(myVar); //=>//["a", "b", "c", callee: function, Symbol(Symbol.iterator): function]
//2
for(m in myVar){
console.log(m); //will generate only the realistic arguments "a","b","c".
}
According to the above snippet, why should the first invoking generate the arguments object with the inherited properties from the Function main object, and the second will generate only the realistic arguments.
If we passed the arguments object to a second function, why should it will be passed with the realistic data only, for example
function foo(something) {
console.log(something); ///=>this will generate number 3 as parameter only, not the rest of the object
return this.a + something;
}
var obj = {
a: 2
};
var bar = function() {
return foo.apply( obj, arguments );
};
var b = bar( 3 ); // 2 3
as pointed in the line of console.log(something), it will generate only the realistic params only
Upvotes: 4
Views: 95
Reputation: 31692
The error in the next example is what is interessting:
function foo() { }
foo.apply(null, 5);
The error says (on google chrome):
CreateListFromArrayLike
is called on non-object.
So apparently apply
calls that function first before passing the arguments to the function, CreateListFromArrayLike
will create a new object (or array) out of the provided one ignoring any non-array-like properties in the process.
Note: On mozilla firefox, it throws a different error, but I think both browsers' engines have the same way of implementing apply
.
Upvotes: 2
Reputation: 328
as @ibrahim mahrir comments, and this article this I discovered that, apply will typecast the object to be an array, and this is an example,
function toArray(args) {
return Array.prototype.slice.call(args);
}
function firstFun(){
console.log(toArray(arguments));
}
firstFun("A","b");
/// this will equal, the second provided example in the question itself, thank @ibrahim and the correct answer belongs to him.
Upvotes: 1