<!DOCTYPE HTML><HTML> <Head> <MetaCharSet= "UTF-8"> <title></title> <Scripttype= "Text/javascript">window.onload= function (){ varobtn=document.getElementById ("btn"); functionfn () {alert ( This); } fn (); Obtn.onclick=fn; } </Script> </Head> <Body> <inputtype= "button"name= "BTN"ID= "BTN"value= "button" /> </Body></HTML>
View Code
This refers to the object that invokes the current method (function), or it can be understood as who let the function run, who is the this.
var obtn = document.getElementById ("btn"function() { this; }
It is clear that the object calling the current anonymous function is OBTN
function () { var obtn = document.getElementById ("btn"); function fn () { this; } fn (); function () { fn (); } }
When another function is called in the Obtn, the FN object is still window.
Understand:
<script type= "Text/javascript" >window.onload=function (){ varABTN = document.getElementsByTagName ("Input"); for(vari = 0; i<abtn.length;i++) {Abtn[i].onclick=function(){ This. Style.backgroundcolor = "Yellow"; } } } </script> View CodeThis refers to the input tag of the OBTN
<script type= "Text/javascript" >window.onload=function (){ varABTN = document.getElementsByTagName ("Input"); varthat =NULL; for(vari = 0; i<abtn.length;i++) {Abtn[i].onclick=function() { that= This; FN (); } } functionfn () {That.style.backgroundColor= "Yellow"; } } </script> View CodeYou can define an empty element by saving the object that corresponds to the current this to an empty element and then implementing it in another function.
<script type= "Text/javascript" >window.onload=function (){ varABTN = document.getElementsByTagName ("Input"); varthat =NULL; for(vari = 0; i<abtn.length;i++) {Abtn[i].onclick=fn; } functionfn () { This. Style.backgroundcolor = "Yellow"; } } </script> View CodeThis is another use.
The study and simple application of JS beginner--this