请帮助我理解以下代码:
向所有对象添加名为“稍后”的方法。该方法用于将来使用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“?
发布于 2011-03-16 02:55:42
apply函数需要一个数组作为它的第二个参数,数组的元素将是要应用的函数的参数。因此,这是:
var args = Array.prototype.slice.apply(arguments, [2]);...says在传递参数2的arguments对象上调用Array的slice方法(即用一个元素(数字2)填充对slice的调用中的arguments对象)。
如果arguments对象有自己的slice方法,那么上面的内容就相当于:
arguments.slice(2);apply技巧是必要的,因为arguments实际上不是Array的实例,也没有slice方法。
这样做是从第三个开始返回一个包含later的arguments对象的所有元素的新数组。这就是它返回['Make is']的原因。
如果实际上只需要arguments中的第三个元素的字符串,那么执行以下操作:
arguments[2];还请注意call的存在,它与apply一样,只是允许您传递一个用于填充arguments对象的值列表,这样您就不必像上面所做的那样将参数包装在数组中:
var args = Array.prototype.slice.call(arguments, 2);发布于 2011-03-16 03:01:34
Javascript中的“参数”是传递给函数的所有参数的类似数组的对象。如果你后来打电话给:
car.later(1000, 'show', 'Make is');“参数”的值将为1000,'show','Make‘,因此数组的单个元素如下:参数为1000,arguments1为'show',arguments2为'Make’。下面是一个页面,它解释了一些关于JavaScript函数中的可选参数:http://www.openjs.com/articles/optional_function_arguments.php,这里有一个很好的页面,介绍了参数对象:https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Using_the_arguments_object
https://stackoverflow.com/questions/5320518
复制相似问题