瀏覽器宿主的全局環境中,this
指的是window
對象。
<script type="text/javascript"> console.log(this === window); //true </script>
瀏覽器中在全局環境下,使用var
聲明變量其實就是賦值給this
或window
。
除了DOM的事件回調或者提供了執行上下文(后面會提到)的情況,函數正常被調用(不帶new
)時,里面的this
指向的是全局作用域。
下面用JavaScript中的this。做一個按鈕選中效果,代碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>按鈕變色</title> <link rel="stylesheet" href="css/Default style sheet.css" /> <style> #box{ margin: 0px auto; height: 60px; width: 600px; border: 2px solid black; line-height: 60px; text-align: center; } #box li{ margin-right:10px; height: 40px; width: 40px; border: 1px solid red; border-radius: 50%; text-align: center; line-height: 40px; float: left; } .active{ background: olive; color: blueviolet; border: 1px solid lightcoral; } </style> <script> window.onload=function(){ var oli=document.getElementsByTagName("li"); for(var i=0;i<oli.length;i++){ oli[i].onclick=function(){ for(var i=0;i<oli.length; i++){ oli[i].className=''; } this.className='active'; } } } </script> </head> <body> <div id="box"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </div> </body> </html>