一. 对于接触前端不太久的时候,相信会有个让大家都感到头疼的问题,没错那就是关于 this 的指向问题。我在刚接触不久的时候也有过这样一段时间,不过大家也不用担心,相信大家只要把这篇博客认真研究一遍,一定会对 this 会有一些新的认识。
函数的调用方式决定了 this 的指向不同:
1. 普通函数调用,此时 this 指向 window
function fn() {
console.log(this); // window
}
fn(); // window.fn(),此处默认省略window
2. 构造函数调用, 此时 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')
3. 对象方法调用, 此时 this 指向 该方法所属的对象
var obj = {
fn: function () {
console.log(this); // obj
}
}
obj.fn();
4.通过事件绑定的方法, 此时 this 指向 绑定事件的对象
btn.onclick = function() {
console.log(this); // btn
}
5. 定时器函数, 此时 this 指向 window
setInterval(function () {
console.log(this); // window
}, 1000);
以上五个方面 就是对函数内部 this 指向的基本整理
关于this 的终极总结 : 函数内部的 this 是由调用时确定其指向。
二. 接下来一起来看一下如何使用bind,call,apply改变 this的指向,以及他们各自一些小的应用
1.bind()会创建一个新的函数(称为绑定函数),与被调用函数有相同的函数体,当目标函数被调用时this