Can somebody please explain why the below code returns undefined 2 times ?
var test = function (theArr) {
alert(theArr);
};
test.call(6); //Undefined
var theArgs = new Array();
theArgs[0] = 6;
test.apply(theArgs) //Undefined
Can somebody please explain why the below code returns undefined 2 times ?
var test = function (theArr) {
alert(theArr);
};
test.call(6); //Undefined
var theArgs = new Array();
theArgs[0] = 6;
test.apply(theArgs) //Undefined
Share
edited Oct 15, 2013 at 12:38
Stephane Rolland
40k38 gold badges126 silver badges172 bronze badges
asked Oct 13, 2011 at 10:43
HerbalMartHerbalMart
1,7393 gold badges27 silver badges50 bronze badges
2
- Why do you need to use the call method? – Jamie Dixon Commented Oct 13, 2011 at 10:46
- You mean that it shows "Undefined" in the alert dialog, right? Because there are not return values anywhere. – Till Helge Commented Oct 13, 2011 at 10:46
1 Answer
Reset to default 8The syntax for the JavaScript call method:
fun.call(object, arg1, arg2, ...)
The syntax for the JavaScript apply method:
fun.apply(object, [argsArray])
The main difference is that call() accepts an argument list, while apply() accepts a single array of arguments.
So if you want to call a function which prints something and pass an object scope for it to execute in, you can do:
function printSomething() {
console.log(this);
}
printSomething.apply(new SomeObject(),[]); // empty arguments array
// OR
printSomething.call(new SomeObject()); // no arguments
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744924632a4601355.html
评论列表(0条)