javascript拾遗(1)

2018-03-03  本文已影响0人  非墨即白

https://www.quirksmode.org/js/this.html

If you want to usethisfor accessing the HTML element that is handling the event,you must make sure that thethiskeyword is actually written into theonclickproperty.Only in that case does it refer to the HTML element the event handler is registeredto. So if you do

element.onclick = doSomething;

alert(element.onclick)

you get

function doSomething()

{

this.style.color = '#cc0000';

}

As you can see, thethiskeyword is present in theonclickmethod.Therefore it refers to the HTML element.

But if you do

alert(element.onclick)

you get

function onclick()

{

doSomething()

}

This is merely a reference to functiondoSomething(). Thethiskeyword is not present in theonclickmethod so it doesn't refer to the HTML element

上一篇 下一篇

猜你喜欢

热点阅读