javascript中this的四種用法
this
在函數(shù)執(zhí)行時,this 總是指向調(diào)用該函數(shù)的對象。要判斷 this 的指向,其實就是判斷 this 所在的函數(shù)屬于誰。
在《javaScript語言精粹》這本書中,把 this 出現(xiàn)的場景分為四類,簡單的說就是:
有對象就指向調(diào)用對象
沒調(diào)用對象就指向全局對象
用new構(gòu)造就指向新對象
通過 apply 或 call 或 bind 來改變 this 的所指。
1) 函數(shù)有所屬對象時:指向所屬對象
函數(shù)有所屬對象時,通常通過 . 表達式調(diào)用,這時 this 自然指向所屬對象。比如下面的例子:
var myObject = {value: 100}; myObject.getValue = function () { console.log(this.value); // 輸出 100 // 輸出 { value: 100, getValue: [Function] }, // 其實就是 myObject 對象本身 console.log(this); return this.value; }; console.log(myObject.getValue()); // => 100
getValue() 屬于對象 myObject,并由 myOjbect 進行 . 調(diào)用,因此 this 指向?qū)ο?myObject。
2) 函數(shù)沒有所屬對象:指向全局對象
var myObject = {value: 100}; myObject.getValue = function () { var foo = function () { console.log(this.value) // => undefined console.log(this);// 輸出全局對象 global }; foo(); return this.value; }; console.log(myObject.getValue()); // => 100
在上述代碼塊中,foo 函數(shù)雖然定義在 getValue 的函數(shù)體內(nèi),但實際上它既不屬于 getValue 也不屬于 myObject。foo 并沒有被綁定在任何對象上,所以當調(diào)用時,它的 this 指針指向了全局對象 global。
據(jù)說這是個設(shè)計錯誤。
3) 構(gòu)造器中的 this:指向新對象
js 中,我們通過 new 關(guān)鍵詞來調(diào)用構(gòu)造函數(shù),此時 this 會綁定在該新對象上。
var SomeClass = function(){ this.value = 100; } var myCreate = new SomeClass(); console.log(myCreate.value); // 輸出100
順便說一句,在 js 中,構(gòu)造函數(shù)、普通函數(shù)、對象方法、閉包,這四者沒有明確界線。界線都在人的心中。
4) apply 和 call 調(diào)用以及 bind 綁定:指向綁定的對象
apply() 方法接受兩個參數(shù)第一個是函數(shù)運行的作用域,另外一個是一個參數(shù)數(shù)組(arguments)。
call() 方法第一個參數(shù)的意義與 apply() 方法相同,只是其他的參數(shù)需要一個個列舉出來。
簡單來說,call 的方式更接近我們平時調(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)文章
javascript 中的 delete及delete運算符
這篇文章主要介紹了javascript 中的 delete及delete運算符的相關(guān)資料,需要的朋友可以參考下2015-11-11JavaScript整除運算函數(shù)ceil和floor的區(qū)別分析
這篇文章主要介紹了JavaScript整除運算函數(shù)ceil和floor的區(qū)別分析,實例分析了ceil和floor函數(shù)的使用技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04javascript實現(xiàn)打磚塊小游戲(附完整源碼)
這篇文章主要為大家詳細介紹了javascript實現(xiàn)打磚塊小游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-09-09