console.log如何工作?

Nea*_*eal 13 javascript console logging

第一个例子:

在下面的例子中:http://jsfiddle.net/maniator/ScTAW/4/
我有这个js:

var storage = (function () {
    var store = [];
    return {
        "add": function (item) {
            store.push(item);
        },
        "get": function () {
            return store;
        }
    };
}());

storage.add('hi there')
console.log(storage, storage.get(), storage.add('hi there #2'));
Run Code Online (Sandbox Code Playgroud)

以下是打印到控制台的内容:

对象["hi there","hi there#2"] undefined

有人会认为控制台应该只说:

对象["hi there"]未定义

becase的第二推也不会发生,直到该值被记录之后,因此它不应该被显示.


第二个例子:

在以下示例中:http://jsfiddle.net/maniator/ScTAW/5/

我使用相同的storage变量,但我记录如下:

storage.add('hi there')
console.log(storage, storage.get(), (function() {
    storage.add('hi there #2');
    console.log('TESTING');
})());
Run Code Online (Sandbox Code Playgroud)

打印到控制台的内容是:

测试
对象["hi there","hi there#2"] undefined

嗯,这很奇怪现在不是吗?人们可以期待看到:

对象["hi there"] undefined
TESTING

为什么会这样?控制台日志记录机制幕后发生了什么?

Jan*_*net 19

在大多数(如果不是全部)命令式编程语言中,必须在调用函数之前评估传递给函数调用的任何参数(所谓的Eager评估).此外,它们通常按从左到右的顺序进行评估(对于C,例如它未定义),但是在两个示例中,参数的计算顺序无关紧要.在查看详细情况时,这应该是非常明显的:

如前所述,在console.log调用之前,storage.get()必须先执行,返回store数组.然后storage.add('hi there #2')将执行(或反过来),所以它的结果(在这种情况下undefined,因为add不返回任何东西)可以作为第三个参数传递给console.log.这意味着console.log将使用参数调用一次(storage, storage.store, undefined),store数组已经包含"hi there#2",从而产生您观察到的结果.

在第二个例子中,推理再次相同,函数调用稍微模糊一些.首先看它看起来有一个函数作为第三个参数传递给console.log函数; 但它实际上是一个函数调用(观察者()在最后).因此storage.add('hi there #2')将执行,然后将匿名函数执行console.log('TESTING')undefined结果再次传递给console.log.

如果您确实将函数传递给了console.log,它将打印该函数定义,而不执行任何操作.所以:

storage.add('hi there')
console.log(storage, storage.get(), (function() {
    storage.add('hi there #2');
    console.log('TESTING');
}));
Run Code Online (Sandbox Code Playgroud)

,没有()最后,导致:

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

我希望这会让事情变得更加清晰.