[js高手之路]this知多少
this關鍵字在javascript中的變化非常的靈活,如果用的不好就非常惡心,用的好,程序就非常的優雅,靈活,飄逸.所以掌握this的用法,是每一個前端工程師必知必會的.而且這個也是一些大公司筆試中常見的考察項.
第一種、單獨的this,指向的是window這個對象
console.log( this ); //window 注:當前的執行環境是window, 所以this指向了window 第二種、全局函數中的this 1 function show(){ 2 alert( this ); //window 3 } 4 show();show()這樣子調用,指向的是window
第三種、函數調用的時候,前面加上new關鍵字,也就是構造函數的調用方式
1 function show(){ 2 alert( this ); //object 3 } 4 new show();new show這樣調用,函數中的this指向的是object
第四種、用call與apply的方式調用函數,這里面的this分兩種情況
- 一般情況下,call與apply后面的第一個參數, 該參數是什么, this就指向什么
- call與apply后面如果是undefined和null,this指向的是window
這里要稍微注意一下, call與apply后面的參數傳遞的區別: call是一個個把參數傳遞給函數的參數,而apply是把參數當做數組傳遞給函數的參數,數組第一項傳遞給函數的第一個參數,第二項傳遞給函數的第二個參數。。。以此類推
第五種、定時器中的this,指向的是window
1 setTimeout( function(){ 2 alert( this ); //window 3 }, 500 );第六種、元素綁定事件,事件觸發后 執行的函數中的this 指向的是當前的元素
1 <input type="button" value="點我"> 2 <script> 3 document.querySelector("input").onclick = function(){ 4 alert(this); //指向當前按鈕 5 }; 6 </script>第七種、函數調用時如果綁定了bind, 那么函數中的this就指向了bind中綁定的東西
1 <input type="button" value="點我"> 2 document.querySelector("input").addEventListener("click", function(){ 3 alert(this); //window 4 }.bind(window));如果沒有通過bind改變this,那么this的指向就會跟第六種情況一樣
第八種、對象中的方法:該方法被哪個對象調用,那么方法中的this就指向該對象
var obj = {userName : "ghostwu",show : function(){return this.userName;}};alert( obj.show() ); //ghostwu如果把對象的方法,賦給一個全局變量,然后再調用,那么this指向的就是window.
1 var obj = { 2 userName : "ghostwu", 3 show : function(){ 4 return this.userName; 5 } 6 }; 7 var fn = obj.show; 8 var userName = 'hello'; 9 alert( fn() );// hello, this指向window學完之后,我們就來應用下,下面這道題是騰訊考察this的面試題,你都能做出來嗎?
1 var x = 20; 2 var a = { 3 x: 15, 4 fn: function () { 5 var x = 30; 6 return function () { 7 return this.x; 8 }; 9 } 10 }; 11 console.log(a.fn()); //function(){return this.x} 12 console.log((a.fn())()); //20 13 console.log(a.fn()()); //20 14 console.log(a.fn()() == (a.fn())()); //true 15 console.log(a.fn().call(this)); // 20 16 console.log(a.fn().call(a)); // 15?
你如果真的搞懂了this,面向對象水平也不錯的話,可以來試試,我的博客中這道騰訊的面試題額:
學生問的一道javascript面試題[來自騰訊]
?
總結
以上是生活随笔為你收集整理的[js高手之路]this知多少的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 以HANA为核心 SAP实时数据平台详解
- 下一篇: 浪潮I9000革新传统刀片 解决基础架构