thisは何を指す?(2)

thisは、
オブジェクトの中ではオブジェクトを指し、
イベントハンドラではイベントが起こったオブジェクトを指す。


それでは、オブジェクトの中のオブジェクトでイベントが起こったときはどうなるだろう。


function Num2(n) {
this.n = n;
this.div = document.getElementById("div1");
this.aNode = document.createElement("a");
this.aNode.href = "javascript:void(0)";
this.aNode.innerHTML = "test2";
this.aNode.onclick = function() { alert(this.n); }
this.aNode.n = 5;
this.div.appendChild(this.aNode);
}

var obj = new Num2(4);

thisがNumオブジェクトを指せば4、
aNodeを指せば5と表示される。


結果は、5。
aNodeの方が内側なので、
ということで面白い結果は出なかった。


じゃあ元のオブジェクトのほうを指したいときはどうすればいいのかというと、こんなカンジか?


this.aNode.obj = this;
this.aNode.onclick = function() { alert(this.obj.n); }