Javascript 函数参数问题
请帮助我理解以下代码: 将名为“later”的方法添加到所有对象。此方法用于将来使用Javascript 函数参数问题,javascript,Javascript,请帮助我理解以下代码: 将名为“later”的方法添加到所有对象。此方法用于将来使用setTimeout调用其他方法 Object.prototype.later = function (msec, method) { // save 'this' as 'that' so we can use 'this' in inner function var that = this; // I cannot understand: what [2] means //
setTimeout
调用其他方法
Object.prototype.later = function (msec, method) {
// save 'this' as 'that' so we can use 'this' in inner function
var that = this;
// I cannot understand: what [2] means
// args will be ['Make is']. How?
var args = Array.prototype.slice.apply(arguments, [2]);
if (typeof method === 'string') {
method = that[method];
}
// now use setTimeout to call method in future
setTimeout(function () { method.apply(that, args); }, msec);
return that;
}
// example of using later method
var car = {};
car.make = 'Ford';
car.show = function (message) {
alert(message + ' ' + this.make);
}
car.later(1000, 'show', 'Make is');
因此,当我们稍后调用car.later
时,第三个参数被传递,并将用于警报功能
问题是:我们如何读取第三个参数“Make is”函数需要一个数组作为其第二个参数,该数组的元素将是所应用函数的参数。那么这个,
var args = Array.prototype.slice.apply(arguments, [2]);
…表示对传入参数2
的arguments
对象调用Array
的slice
方法(即在调用slice
的arguments
对象中填充一个元素,即数字2)
如果参数
对象有自己的切片
方法,则上述方法相当于此:
arguments.slice(2);
应用
技巧是必要的,因为参数
实际上不是数组
的实例,并且没有切片
方法
这样做的目的是返回一个新数组,该数组从第三个开始包含later
sarguments
object的所有元素。这就是它返回['Make is']
的原因
如果您实际上只需要作为参数
中第三个元素的字符串,请执行以下操作:
arguments[2];
另请注意,call
的存在,它与apply
类似,只是它允许您传递用于填充参数
对象的值列表,这样您就不必像上面那样将参数包装到数组中:
var args = Array.prototype.slice.call(arguments, 2);
Javascript中的“参数”是传递到函数中的所有参数的类似数组的对象。如果您稍后致电:
car.later(1000, 'show', 'Make is');
“arguments”的值将是[1000,'show','Make's],因此数组的各个元素如下:arguments[0]是1000,arguments[1]是'show',arguments[2]是'Make's'。这里有一个页面解释了JavaScript函数中的一些可选参数:这里有一个很好的页面介绍了arguments对象:+1,用于向我指出参数不是真正的数组。我非常感谢您的回答!你的帖子让我明白了。现在我想知道昨天我怎么不明白:)谢谢