开发者

function.arguments question

Please help me to understand following code:

Add method called 'later' to all objects. This method is used to call other method in future using 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');

So, when we call car.later, the third parameter is passed and will be u开发者_如何学Pythonsed in alert function

Question is: how do we read third parameter "Make is"?


The apply function expects as its second argument an array whose elements will be the arguments to the function being applied. So, this:

var args = Array.prototype.slice.apply(arguments, [2]);

...says to call Array's slice method on the arguments object passing in the argument 2 (i.e. populate the arguments object in the call to slice with one element, the number 2).

If the arguments object had its own slice method, then the above would be equivalent to this:

arguments.slice(2);

The apply trick is necessary because arguments is not really an instance of Array and does not have a slice method.

What this does is return a new array having all elements of laters arguments object from the third on. That's why it returns ['Make is'].

If you actually just want the string that is the third element in arguments, then do this:

arguments[2];

Note also the existence of call, which is just like apply except that it allows you to pass a list of values to use to populate the arguments object, so that you don't have to wrap your argument in an array as you've done above:

var args = Array.prototype.slice.call(arguments, 2);


The "arguments" in Javascript is an array-like object of all the arguments passed into a function. In the case of your call to later:

car.later(1000, 'show', 'Make is');

The value of "arguments" will be [1000, 'show', 'Make is'], so the individual elements of the array are as follows: arguments[0] is 1000, arguments[1] is 'show', and arguments[2] is 'Make is'. Here is a page that explains some about optional arguments in JavaScript functions: http://www.openjs.com/articles/optional_function_arguments.php and here's a good one that goes into the arguments object: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Using_the_arguments_object

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜