Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

javascript - Why should use "apply"?

This snippet is cut from Secrets of the JavaScript Ninja.

function log() {
    try {
        console.log.apply( console, arguments );
    } catch(e) {
        try {
            opera.postError.apply( opera, arguments );
        } catch(e){
            alert( Array.prototype.join.call( arguments, " " ) );
        }
    }
}

Why should I use apply and what's the difference between console.log.apply(console, arguments) and console.log(arguments)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In this case, the log function may accept any number of arguments.

Using .apply(), it doesn't matter how many arguments are passed. You can give the set to console.log(), and they will arrive as individual arguments.

So if you do:

console.log(arguments)

...you're actually giving console.log a single Arguments object.

But when you do:

console.log.apply( console, arguments );

...it's as though you passed them separately.

Other useful examples of using .apply() like this can be demonstrated in other methods that can accept a variable number of arguments. One such example is Math.max().

A typical call goes like this:

var max = Math.max( 12,45,78 );  // returns 78

...where it returns the largest number.

What if you actually have an Array of values from which you need the largest? You can use .apply() to pass the collection. Math.max will think they were sent as separate arguments instead of an Array.

var max = Math.max.apply( null, [12,45,92,78,4] );  // returns 92

As you can see, we don't need to know in advance how many arguments will be passed. The Array could have 5 or 50 items. It'll work either way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...