0

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?

000
27.3k10 gold badges74 silver badges103 bronze badges
asked Jul 12, 2013 at 11:36

4 Answers 4

4

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

answered Jul 12, 2013 at 11:41
Sign up to request clarification or add additional context in comments.

Comments

2

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 />";
answered Jul 12, 2013 at 11:43

Comments

2

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/

answered Jul 12, 2013 at 11:46

Comments

1

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 />";
answered Jul 12, 2013 at 11:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.