all和apply的作用很简单,就是改变上下文,主要区别就是调用的方式不一样。
我们可以用apply完成一些方便的操作,比如求数组的最大值:
Math.max.apply(null, [1,2,3,4])
还可以用apply完成数组的合并:
[].push.apply(a, b)
jQuery 中的类型判断也运用了call:
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
//core_toString就是{}.toString
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
core_toString.call([1,2])返回的实际上是"[object array]",jQuery源码内部将这样形式的字符串还对应了一个更可读的array,class2type对象就是一个映射:
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
当参数明确时可用call, 当参数不明确时可用apply给合arguments。