为什么要将'null'传递给'apply'或'call'? [英] Why would you pass 'null' to 'apply' or 'call'?
问题描述
根据此JavaScript参考 :
值null是表示null或空
值的JavaScript文字,即不存在对象值。它是JavaScript的
原始值之一。
The value null is a JavaScript literal representing null or an "empty" value, i.e. no object value is present. It is one of JavaScript's primitive values.
function getMax(arr){
return Math.max.apply(null, arr);
}
不会显式传递关键字 this
更清楚,或者至少更具可读性?然后,在这一点上,我可能不明白你为什么要使用 null
。
Wouldn't explicitly passing the keyword this
be clearer, or at least more readable? Then again, at this point I may not understand why you would use null
.
推荐答案
使用null调用 apply
,因为第一个参数就像调用函数而没有为这个
提供任何对象。
Calling apply
with null as the first argument is like calling the function without providing any object for the this
.
适用
方法做什么?
apply()
方法调用具有给定此
值和$ b的函数$ barguments
以数组(或类数组的对象)的形式提供。
The
apply()
method calls a function with a giventhis
value andarguments
provided as an array (or an array-like object).
fun.apply(thisArg, [argsArray])
thisArg
thisArg
为乐趣召唤提供的价值。请注意,这可能不是
是方法看到的实际值:如果该方法是
非严格模式代码中的函数,则null和undefined将替换为
全局对象,和原始值将被装箱。
The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.
可以找到更多文档 here 。
这篇关于为什么要将'null'传递给'apply'或'call'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!