函數上下文
Jquery函數的上下文是什麼,取決于函數的調用而不是函數的定義。
情況
- 函數+圓括号直接調用
注意:内部的this是window對象function add(){ console.log(this) } add();
jQuery函數上下文函數上下文情況 - 對象.函數();調用
注意:内部的this是是這個對象var arr={ name:'helloworld', play:function(){ console.log(this); } } arr.play();
jQuery函數上下文函數上下文情況 - 函數作為事件處理函數
注意:内部的this是觸發這個事件的元素var more = document.querySelector(".more"); more.onclick = function () { console.log( this ); };
jQuery函數上下文函數上下文情況 - 定時器調用函數
注意:内部的this是window對象setTimeout(function () { console.log(this); },1000);
jQuery函數上下文函數上下文情況 - 調用從數組中索引的函數
注意:内部的this表示數組本身var arr = [10,20,30, function () { console.log( this ); }]; arr[3]();//[10, 20, 30, ƒ]
jQuery函數上下文函數上下文情況