开发者

JavaScript from John Resig Learning Advanced JavaScript #45

function highest(){ 
          return makeArray(arguments).sort(function(a,b){ 
            return b - a; 
          }); 
        } 

function makeArray(array){ 
  re开发者_JAVA技巧turn Array().slice.call( array ); 
} 

assert(highest(1, 1, 2, 3)[0] == 3, "Get the highest value."); 
assert(highest(3, 1, 2, 3, 4, 5)[1] == 4, "Verify the results.");

This example is #45 from John Resig`s Learning Advanced JavaScript. http://ejohn.org/apps/learn/#45

Here are some questions which I would appreciate some help with. Thanks in advance.

1). when function highest() returns makeArray(arguments), does function makeArray take place before the sort function in function highest? So that after makeArray() runs, the remaining part

sort(function(a,b){ 
    return b - a;

of function highest continues and the sort takes place on the Array returned from makeArray?

2) In function makeArray(array), what exactly is "call" calling?

3) In function makeArray, is slice used because call takes its arguments separately rather than as an array?

4) In the final assert, does the [1] represent the location in an array of the 4 > i.e. after the sort there is an array ['5','4','3','3','2','1']


  1. Yes, that's exactly right. These actions happen in sequence.

  2. It's calling Array.prototype.slice and passing array which is the arguments object of highest. When called with no arguments, slice simply returns a copy the object it's working on. This is how we convert the array-like arguments object to an actual array.

  3. See #2. slice and call are used in tandem to produce a copy of arguments that's an actual array.

  4. Yes, again, you're correct. The highest function returns an array containing its arguments sorted in descending order.


As I was answering this, another answer was posted. But I think that most of the confusion shown in the question comes down to one key point.

In JavaScript, functions and methods are objects. Which may have properties, etc. When you say Array.slice you get the slice method. When you say Array.slice() you now are calling the slice method. So Array.slice.call accesses the call property of the slice method on the Array object. (That property happens to be a method in its own right.) And Array.slice.call( stuff ) calls that.

That's a pretty fundamental fact of the language which is easy to miss. But if you don't understand that point, you'll find code that uses it virtually impossible to actually understand.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜