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
166 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)?

question from:https://stackoverflow.com/questions/66049496/what-is-this-function-for

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

1 Answer

0 votes
by (71.8m points)

If you have

function log() {
    console.log.apply(console, arguments);
}

and call it like log('foo'); then that translates to console.log.apply(console, ['foo']); which is equivalent to console.log('foo'); which is what you want.

If you defined it like

function log() {
    console.log(arguments);
}

instead then log('foo'); would be equivalent to log(['foo']); which is not what you want.


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

...