DIV CSS 佈局教程網

JavaScript 中 this 關鍵字的用法實解
編輯:關於JavaScript     

本文透過多個實例,系統性地分析 JavaScript 中 this 的四種常見用法。

實例一:以函式形式呼叫

此時 this 代表全域物件 window。

<script type="text/javascript">
function t(){
  alert(this); // 這裡 this 表示 window 物件
}
t();
</script>

實例二:以物件屬性的形式呼叫

此時 this 代表該物件。範例中 onclick 為 p 元素物件的屬性。

<html>
<head>
<script type="text/javascript">
function t(){
  alert(this);
  this.style.background = 'green';
}
window.onload = function(){
  document.getElementById('eng').onclick = t;
}
</script>
</head>
<body>
<p id="eng">abcd</p>
</body>
</html>

實例三:以建構器的方式呼叫

<script type="text/javascript">
function dog(){
  this.legs = 4;
  this.bark = function(){ alert("汪汪..."); }
}
var wangcai = new dog(); // 以 new 函式名() 建立物件
wangcai.bark();
</script>

說明:(1)若直接呼叫 dog() 而非以建立物件的方式呼叫,則等同第一種情況,this 代表 window。(2)JS 中沒有「類」的概念,但有「物件」的概念。(3)物件可用 var obj = {name:'abc',age:40} 建立,也可透過建構函式建立。(4)當一個普通函式以「new 函式名()」的方式呼叫時,它就充當建構函式。

實例四:call 與 apply 方式

<html>
<head>
<script type="text/javascript">
window.onload = function(){
 var hi = document.getElementById('hi');
 if(hi.addEventListener){ // chrome 與 firefox
  hi.addEventListener('click',function(){alert(this.id)},false); // W3C 模型中 this 指向 DOM 物件,結果為 hi
 }else{ // ie
  hi.attachEvent('onclick',function(){alert(this.id)}); // IE8 及以下 this 指向 window,結果為 undefined
 }
}
</script>
</head>
<body>
<p id="hi">hello world</p>
</body>
</html>

理解 this 在不同呼叫情境下的指向,是掌握 JavaScript 物件導向的關鍵。希望本文對你的程式設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved