1. 给当前元素的某个事件绑定方法,方法中的this 都是当前操作的元素本身
document.body.onclick = function () {
//this : body
}
2. 函数执行,看函数前面是否有点,有的话点前面的this 就是谁,没有点, this就是window 在js的严格模式下,没有点的this是undefined
let fn = function () {
console.log(this.name)
};
let obj = {
name : 'hh',
fn: fn
};
fn(); //this: window
obj.fn();//this : obj
3.构造函数执行 方法中的this 一般都是当前类的实例
let Fn = function () {
this.x = 100; //this:f
}
let f = new Fn;
4.箭头函数中没有自己的this this 是上下文中的this
let obj = {
fn: function() {
setTimeout(() => {
//this: obj
},1000);
}
}
obj.fn();
5.在小括号表达式中 会影响this 的指向
let obj = {
fn:function () {
console.log(this);
}
};
obj.fn(); //this : obj
(23, obj.fn)();//this :window
6.使用call/apply/bind可以改变 this 指向
fn.call(obj);//this obj
fn.call(12);//this :12
fn.call(); //this:window 非严格模式下call/apply/bind第一个参数不写或者写 null和undefined this都是window 严格模式下写谁this 就是谁,不写是undefined