strange behaviour

by John Doe

HTML

<div id="foo">

</div>
<div id="bar">

</div>

JavaScript

function test(){

  var foo = document.getElementById("foo")
  var bar = document.getElementById("bar")
	for(var k=0; k < 2; k++){
  
    // 1st example
    var a = document.createElement("button")
    a.innerHTML = "A button "+k
    var str = "click " + k
    a.onclick = function(){alert(str)}
    
    //2nd example
    foo.appendChild(a)
    var b = document.createElement("button")
    b.innerHTML = "B button "+k
    b.onclick = function(){alert("click " + k)}
    bar.appendChild(b)
  }
}

test()