js中的this的指向
-
在普通函数中,this指向window
function fn() { console.log(this); // window } fn(); // window.fn(),此处默认省略window
-
在构造函数中,this指向创建的对象
function Person(age, name) { this.age = age; this.name = name console.log(this) // 此处 this 分别指向 Person 的实例对象 p1 p2 } var p1 = new Person(18, 'zs') var p2 = new Person(18, 'ww')
-
在方法声明中,this指向调用者
var obj = { fn: function () { console.log(this); // obj } } obj.fn();
-
通过事件绑定的方法, 此时 this 指向 绑定事件的对象
<body> <button id="btn">hh</button> <script> var oBtn = document.getElementById("btn"); oBtn.onclick = function() { console.log(this); // btn } </script> </body>
-
在定时器中, this指向window
setInterval(function () { console.log(this); // window }, 1000);
最后结论:
- 所有的this关键字,在函数运行时,才能确定它的指向
- this所在的函数由哪个对象调用,this就会指向谁
- 当函数执行时,没有明确的调用对象时,则this指向window
定时器中如何改变this指向
btn.onclick = function(){
setTimeout(function(){
console.log(this);
},0)
}
btn.onclick();
- 我们期待this指向btn,而this现在却指向了window
- 这个问题该怎么修复呢? 有很多办法
- 可以使用call、apply、bind改变this指向
- 如果你不知道call、apply、bind,那么恐怕你只能看得懂方法A
//方法A btn.onclick = function(){ var self = this; //使用变量保存this,self变量的值是不会随着环境改变的 setTimeout(function(){ console.log(self); },0) } btn.onclick();
- call
//方法B btn.onclick = function(){ var self = this; //使用变量保存this function fn(){ //将代码写在一个函数fn中 console.log(this); } setTimeout(function(){ fn.call(self); //强行指定this为self对象 },0) } btn.onclick(); /* call方法的作用,是调用函数,同时指定this可以代表谁 例如 fn.call(obj) 意思就是 调用函数fn,并且this指向obj对象 */
- apply
//方法C btn.onclick = function(){ var self = this; //使用变量保存this function fn(){ //将代码写在一个函数fn中 console.log(this); } setTimeout(function(){ fn.apply(self); //使用apply方法调用函数,强行指定this为self对象 },0) } btn.onclick(); /* apply方法的作用,是调用函数,同时指定this可以代表谁 例如 fn.apply(obj) 意思就是 调用函数fn,并且this指向obj对象 */
- bind
//方法D btn.onclick = function(){ setTimeout(function(){ console.log(this); }.bind(this), 0 ) //使用bind方法,将定时器函数的this强行绑定为事件函数的this } btn.onclick(); /* bind方法的作用,是绑定函数的this,同时返回绑定后的新函数 例如 var fb = fn.bind(obj); window.fb(); 无论谁调用fb函数, 函数的this都会指向obj */
- 特殊情况
-
如何判断箭头函数的this?
-
因为箭头函数不具备自己的this,所以非常简单,假装它不存在,就像这样:
-
这下this的指向非常清晰了吧
-
-
箭头函数可以用call来改变this指向吗?
- 不能!! 试图改变箭头函数的this是徒劳的。
-