this是javascript语言的一个关键字,在函数运行时,自动生成一个内部对象,只能在函数内部使用.随着函数的使用场合不同,this的值也在不断发生变化,(熟记口诀:指向是不确定的,谁调用this指向谁.)
this绑定规则:
1.利用函数名调用函数, 此时 this 指向 它的调用者
function fn(){
console.log(this)
}
fn(); //输出为Window 相当于Window.fn()
2.利用对象调用函数, 此时 this 指向 该方法所属的对象
var obj = {
name: 'zs',
age: 18
}
obj.fn = function () {
console.log(this);
}
obj.fn(); //输出为一个对象{name: 'zs', age: 18, fn: ƒ}
3.定时器调用函数,此时 this指向window
setTimeout(function () {
console.log(this);
}, 1000) //相当于window.setTimeout()
4.调用事件处理函数,此时 this 指向 绑定事件的对象
button.onclick = function(){
console.log(this) //this指向事件源
} //输出为 <button>按钮</button>
5.箭头函数的this指向包裹它的最近的一级函数
6.构造函数的this指向它的实例化对象
7.改变函数内部this指向的三种方法及区别
三种方法: call() apply() bind()