函数上下文
Jquery函数的上下文是什么,取决于函数的调用而不是函数的定义。
情况
- 函数+圆括号直接调用
function add(){ console.log(this) } add();
注意:内部的this是window对象
-
对象.函数();调用
注意:内部的this是是这个对象var arr={ name:'helloworld', play:function(){ console.log(this); } } arr.play();
-
函数作为事件处理函数
var more = document.querySelector(".more"); more.onclick = function () { console.log( this ); };
注意:内部的this是触发这个事件的元素
-
定时器调用函数
setTimeout(function () { console.log(this); },1000);
注意:内部的this是window对象
-
调用从数组中索引的函数
var arr = [10,20,30, function () { console.log( this ); }]; arr[3]();//[10, 20, 30, ƒ]
注意:内部的this表示数组本身