How does console.log work?

后端 未结 4 612
清歌不尽
清歌不尽 2021-02-04 08:22

First Example:

In the following example: http://jsfiddle.net/maniator/ScTAW/4/
I have this js:

var storage = (function () {
    var store = [];
            


        
4条回答
  •  猫巷女王i
    2021-02-04 09:02

    In most (if not all) imperative programming languages, any arguments passed to a function call have to be evaluated before the function can be called (so called Eager evaluation). Also, they are in general evaluated in order from left to right (for C for instance it's undefined), however in both examples the order in which the arguments are evaluated does not matter. This should be pretty obvious when looking at what happens in detail:

    As mentioned, before console.log can be called, storage.get() has to be executed first, returning the store array. Then storage.add('hi there #2') will be executed (or the other way round), so its result (in this case undefined, since add does not return anything) can be passed as the third argument to console.log. This means that the once console.log will be called with the arguments (storage, storage.store, undefined), the store array already contains "hi there #2", hence producing the results you observe.

    In the second example the reasoning is again the same, the function call is just a bit more obscured. On first look it looks there is a function passed as a 3rd argument to the console.log function; but it's actually a function call (observer the () at the end). So storage.add('hi there #2') will be executed, then console.log('TESTING') and then the undefined result from the anonymous function execution will be again passed to console.log.

    If you did actually pass a function to console.log, it would print that function definition, and not execute anything. So:

    storage.add('hi there')
    console.log(storage, storage.get(), (function() {
        storage.add('hi there #2');
        console.log('TESTING');
    }));
    

    , without the () at the end, results in:

    Object
     ["hi there"] function () {
        storage.add('hi there #2');
        console.log('TESTING');
    }
    

    I hope this makes things a bit clearer.

提交回复
热议问题