篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Why invoke apply instead of calling function directly?相关的知识,希望对你有一定的参考价值。
I think the explanation from the Mozilla Docs describes it well:
You can assign a different this object when calling an existing function. this refers to the current object, the calling object. With apply, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
apply is very similar to call, except for the type of arguments it supports. You can use an arguments array instead of a named set of parameters. With apply, you can use an array literal, for example, fun.apply(this, [name, value]), or an Array object, for example, fun.apply(this, new Array(name, value)).
As for the parameters:
thisArg Determines the value of this inside fun. If thisArg is null or undefined, this will be the global object. Otherwise, this will be equal to Object(thisArg) (which is thisArg if thisArg is already an object, or a String, Boolean, or Number if thisArg is a primitive value of the corresponding type). Therefore, it is always true that typeof this == "object" when the function executes.
argsArray An argument array for the object, specifying the arguments with which fun should be called, or null or undefined if no arguments should be provided to the function.
The docs give a good example of a use case for apply. In the example below, apply is used to chain a constructor:
function product(name, value)
{
this.name = name;
if (value >= 1000)
this.value = 999;
else
this.value = value;
}
function prod_dept(name, value, dept)
{
this.dept = dept;
product.apply(this, arguments);
}
prod_dept.prototype = new product();
// since 5 is less than 1000 value is set
var cheese = new prod_dept("feta", 5, "food");
// since 5000 is above 1000, value will be 999
var car = new prod_dept("honda", 5000, "auto");
Notice that in the prod_dept constructor, the this supplied refers to the prod_dept object, and arguments is an array of arguments passed to the product constructor.
var divs = document.getElementsByTagName(‘div‘);
var first_three_div = divs.slice(3) // TypeError: divs.slice is not a function
var first_three_div = Array.prototype.slice.call(divs, 3); // ok