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

javascript中this的四種用法

 更新時(shí)間:2015年05月11日 10:38:58   投稿:hebedich  
在javascript當(dāng)中每一個(gè)function都是一個(gè)對(duì)象,所以在這個(gè)里var temp=this 指的是function當(dāng)前的對(duì)象。this是Javascript語言的一個(gè)關(guān)鍵字。它代表函數(shù)運(yùn)行時(shí),自動(dòng)生成的一個(gè)內(nèi)部對(duì)象,只能在函數(shù)內(nèi)部使用。

this

在函數(shù)執(zhí)行時(shí),this 總是指向調(diào)用該函數(shù)的對(duì)象。要判斷 this 的指向,其實(shí)就是判斷 this 所在的函數(shù)屬于誰。

在《javaScript語言精粹》這本書中,把 this 出現(xiàn)的場景分為四類,簡單的說就是:

有對(duì)象就指向調(diào)用對(duì)象
沒調(diào)用對(duì)象就指向全局對(duì)象
用new構(gòu)造就指向新對(duì)象
通過 apply 或 call 或 bind 來改變 this 的所指。

1) 函數(shù)有所屬對(duì)象時(shí):指向所屬對(duì)象

函數(shù)有所屬對(duì)象時(shí),通常通過 . 表達(dá)式調(diào)用,這時(shí) this 自然指向所屬對(duì)象。比如下面的例子:

var myObject = {value: 100};
myObject.getValue = function () {
 console.log(this.value); // 輸出 100

 // 輸出 { value: 100, getValue: [Function] },
 // 其實(shí)就是 myObject 對(duì)象本身
 console.log(this);

 return this.value;
};

console.log(myObject.getValue()); // => 100

getValue() 屬于對(duì)象 myObject,并由 myOjbect 進(jìn)行 . 調(diào)用,因此 this 指向?qū)ο?myObject。

2) 函數(shù)沒有所屬對(duì)象:指向全局對(duì)象

var myObject = {value: 100};
myObject.getValue = function () {
 var foo = function () {
  console.log(this.value) // => undefined
  console.log(this);// 輸出全局對(duì)象 global
 };

 foo();

 return this.value;
};

console.log(myObject.getValue()); // => 100

在上述代碼塊中,foo 函數(shù)雖然定義在 getValue 的函數(shù)體內(nèi),但實(shí)際上它既不屬于 getValue 也不屬于 myObject。foo 并沒有被綁定在任何對(duì)象上,所以當(dāng)調(diào)用時(shí),它的 this 指針指向了全局對(duì)象 global。

據(jù)說這是個(gè)設(shè)計(jì)錯(cuò)誤。

3) 構(gòu)造器中的 this:指向新對(duì)象

js 中,我們通過 new 關(guān)鍵詞來調(diào)用構(gòu)造函數(shù),此時(shí) this 會(huì)綁定在該新對(duì)象上。

var SomeClass = function(){
 this.value = 100;
}

var myCreate = new SomeClass();

console.log(myCreate.value); // 輸出100

順便說一句,在 js 中,構(gòu)造函數(shù)、普通函數(shù)、對(duì)象方法、閉包,這四者沒有明確界線。界線都在人的心中。

4) apply 和 call 調(diào)用以及 bind 綁定:指向綁定的對(duì)象

apply() 方法接受兩個(gè)參數(shù)第一個(gè)是函數(shù)運(yùn)行的作用域,另外一個(gè)是一個(gè)參數(shù)數(shù)組(arguments)。

call() 方法第一個(gè)參數(shù)的意義與 apply() 方法相同,只是其他的參數(shù)需要一個(gè)個(gè)列舉出來。

簡單來說,call 的方式更接近我們平時(shí)調(diào)用函數(shù),而 apply 需要我們傳遞 Array 形式的數(shù)組給它。它們是可以互相轉(zhuǎn)換的。

var myObject = {value: 100};

var foo = function(){
 console.log(this);
};

foo(); // 全局變量 global
foo.apply(myObject); // { value: 100 }
foo.call(myObject); // { value: 100 }

var newFoo = foo.bind(myObject);
newFoo(); // { value: 100 }

以所述就是本文的全部內(nèi)容了,希望大家能夠喜歡。

相關(guān)文章

最新評(píng)論