Her*_*art 3 javascript parameters function call undefined
有人可以解释为什么下面的代码返回undefined 2次?
var test = function (theArr) {
alert(theArr);
};
test.call(6); //Undefined
var theArgs = new Array();
theArgs[0] = 6;
test.apply(theArgs) //Undefined
Run Code Online (Sandbox Code Playgroud)
JavaScript调用方法的语法:
fun.call(object, arg1, arg2, ...)
JavaScript apply方法的语法:
fun.apply(object, [argsArray])
主要区别在于call()接受参数列表,而apply()接受单个参数数组.
因此,如果您想调用一个打印内容并传递对象作用域的函数来执行,您可以执行以下操作:
function printSomething() {
console.log(this);
}
printSomething.apply(new SomeObject(),[]); // empty arguments array
// OR
printSomething.call(new SomeObject()); // no arguments
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2023 次 |
| 最近记录: |