欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ECMAScript 對象作用域

  • 對象類型

關(guān)鍵字 this

this 的功能

在 ECMAScript 中,要掌握的最重要的概念之一是關(guān)鍵字 this 的用法,它用在對象的方法中。關(guān)鍵字 this 總是指向調(diào)用該方法的對象,例如:

var oCar = new Object;
oCar.color = "red";
oCar.showColor = function() {
  alert(this.color);
};

oCar.showColor();		//輸出 "red"

TIY

在上面的代碼中,關(guān)鍵字 this 用在對象的 showColor() 方法中。在此環(huán)境中,this 等于 oCar。下面的代碼與上面的代碼的功能相同:

var oCar = new Object;
oCar.color = "red";
oCar.showColor = function() {
  alert(oCar.color);
};

oCar.showColor();		//輸出 "red"

TIY

使用 this 的原因

為什么使用 this 呢?因?yàn)樵趯?shí)例化對象時(shí),總是不能確定開發(fā)者會(huì)使用什么樣的變量名。使用 this,即可在任何多個(gè)地方重用同一個(gè)函數(shù)。請思考下面的例子:

function showColor() {
  alert(this.color);
};

var oCar1 = new Object;
oCar1.color = "red";
oCar1.showColor = showColor;

var oCar2 = new Object;
oCar2.color = "blue";
oCar2.showColor = showColor;

oCar1.showColor();		//輸出 "red"
oCar2.showColor();		//輸出 "blue"

TIY

在上面的代碼中,首先用 this 定義函數(shù) showColor(),然后創(chuàng)建兩個(gè)對象(oCar1 和 oCar2),一個(gè)對象的 color 屬性被設(shè)置為 "red",另一個(gè)對象的 color 屬性被設(shè)置為 "blue"。兩個(gè)對象都被賦予了屬性 showColor,指向原始的 showColor () 函數(shù)(注意這里不存在命名問題,因?yàn)橐粋(gè)是全局函數(shù),而另一個(gè)是對象的屬性)。調(diào)用每個(gè)對象的 showColor(),oCar1 輸出是 "red",而 oCar2 的輸出是 "blue"。這是因?yàn)檎{(diào)用 oCar1.showColor() 時(shí),函數(shù)中的 this 關(guān)鍵字等于 oCar1。調(diào)用 oCar2.showColor() 時(shí),函數(shù)中的 this 關(guān)鍵字等于 oCar2。

注意,引用對象的屬性時(shí),必須使用 this 關(guān)鍵字。例如,如果采用下面的代碼,showColor() 方法不能運(yùn)行:

function showColor() {
  alert(color);
};

如果不用對象或 this 關(guān)鍵字引用變量,ECMAScript 就會(huì)把它看作局部變量或全局變量。然后該函數(shù)將查找名為 color 的局部或全局變量,但是不會(huì)找到。結(jié)果如何呢?該函數(shù)將在警告中顯示 "null"。