using "this" or explicit object in javascript

时间:2016-10-20 13:01:21

标签: javascript

This is the javascript code I have,

for (var i=0;i<divList.length;i++){
    divList[i].style.backgroundColor="#AA0000";

    divList[i].onclick = function(){
        this.style.backgroundColor="#00AA00";
    }
}

I'm just wondering why I can't use

divList[i].style.backgroundColor="#00AA00";

2 个答案:

答案 0 :(得分:3)

Theoretically, you could, but practically, you can't for a simple reason.

By the time that onclick function gets called, the value of divList and i will not be what you expect them to. i will be inherited by lexical scope, and it would be the same i for all of the onclick handlers, and it would be divList.length because that's the last value that got assigned to it.

Essentially, you would try to set the color of the Nth div to green, but you only have N-1 items.

There are several ways you could overcome that, but the simplest course of action would be to just use this. The JavaScript engine would call your function and bind this to the element that triggered the event, in this case, it would be the div element that got clicked.

答案 1 :(得分:0)

Here is some more information about this topic:

(Point 6) https://www.toptal.com/javascript/10-most-common-javascript-mistakes

This is because, by the time onclick is invoked for any of the elements, the for loop will have completed and the value of i will already be 10 (for all of them).

Test it out: (Notice the console.log and the green box)

var divList = document.getElementsByTagName("DIV");

    for (var i=0;i<divList.length;i++){
        divList[i].style.backgroundColor="red";

        divList[i].onclick = function () {
            this.style.backgroundColor="blue";
          divList[i-1].style.backgroundColor = "green";
            console.log("i:", i, "element:", i-1);
        }
    }
<div>foo 0</div>
<div>foo 1</div>
<div>foo 2</div>
<div>foo 3</div>
<div>foo 4</div>
<div>foo 5</div>
<div>foo 6</div>
<div>foo 7</div>
<div>foo 8</div>
<div>foo 9</div>