函数调用行为

时间:2013-07-12 11:36:29

标签: javascript

在我的测试中,mylog函数被调用三次,但是查看源代码我想它应该只执行两次。

<html>
<div id='log'></div>
<script>

var Foo = { counter : "inside the Foo object" };
var counter = "Global";

Foo.method = function() {
    var counter = "inside Foo.method";
    mylog("counter = "+this.counter);
    function test() {
        // this is set to the global object
        mylog("counter = "+this.counter);
    }
    test();
}

Foo.method();

function mylog(msg) {
    log = document.getElementById("log");
    log.innerHTML += log.innerHTML + msg + "<br />";
}
</script>
</html>

http://jsfiddle.net/8BBF7/

这是输出:

counter = inside the Foo object
counter = inside the Foo object
counter = Global

据我所知,预期mylog函数只被调用两次。有人可以解释一下为什么会这样吗?

4 个答案:

答案 0 :(得分:4)

只需将+=更改为=log.innerHTML += log.innerHTML + msg + "<br />";或保留,然后使用表格log.innerHTML += msg + "<br />";

答案 1 :(得分:2)

那是因为这个

log.innerHTML += log.innerHTML + msg + "<br />";

您还添加了当前的innerHTML,因此您可以复制早期的日志。这样做

log.innerHTML += msg + "<br />";

log.innerHTML = log.innerHTML + msg + "<br />";

答案 2 :(得分:2)

该函数被调用了2次,但是在添加log.InnerHTML时出错了。你追加log.innerHTML 2次

工作代码:

function mylog(msg) {
    log = document.getElementById("log");
    log.innerHTML +=  msg + "<br />";
}

请参阅http://jsfiddle.net/8BBF7/16/

答案 3 :(得分:1)

它只被叫了两次。检查您的mylog()

function mylog(msg) {
    log = document.getElementById("log");
    log.innerHTML += log.innerHTML + msg + "<br />";
}

使用

log.innerHTML = log.innerHTML + msg + "<br />";

log.innerHTML += msg + "<br />";