freedev
freedev

Reputation: 30197

Function call behavior

In my test the mylog function is called three times, but looking at source I suppose it should be executed only twice.

<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/

This is the output:

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

As told I expected mylog function is called only twice. Can someone explain me why this is happening?

Upvotes: 0

Views: 186

Answers (4)

Doua Beri
Doua Beri

Reputation: 10949

The function is called 2 times, but you made a mistake on appending log.InnerHTML . You append log.innerHTML 2 times

Working code:

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

See http://jsfiddle.net/8BBF7/16/

Upvotes: 2

Willem Mulder
Willem Mulder

Reputation: 14014

That's because of this

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

You add the current innerHTML as well, so you duplicate earlier logs. Do it like this

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

or

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

Upvotes: 2

sjngm
sjngm

Reputation: 12871

It's only called twice. Check your mylog():

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

Either use

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

or

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

Upvotes: 1

Brandon J. Boone
Brandon J. Boone

Reputation: 16472

Just change the += to an = on the line log.innerHTML += log.innerHTML + msg + "<br />"; or keep it and use the form log.innerHTML += msg + "<br />";

Upvotes: 4

Related Questions