Can somebody please explain why the开发者_如何学Go 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
The 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
精彩评论