(前言:小编也是一个刚入行的小白,所以写不出来多么高深的东西,若有错误欢迎指证或者其他的什么相互验证,但是不接受大神的鄙视,谢谢,转载请注明出路)
1.给元素绑定事件时,this就是当前操作元素
box.onclick=function () {
console.log(this); // this => 单击的元素
}
2.普通函数中,函数执行前面有点this就指代点前面的对象,没有点就指向全局window(非严格模式下),严格模式下为undefined
function fn(){
console.log(this);
}
let obj={};
obj.fn=fn;
fn() //=> this=>window,严格模式下为undefined
obj.fn() // this=>window
3.构造函数中,this指向当次操作中的实例
function Fn(){
console.log(this); // this => Fn构造函数当前运行创建的实例
}
4.全局环境下的this指向全局window
console.log(this); // this => window
5.自执行函数中的this始终指向全局window
~(function () {
console.log(this); // this => window
})()
6.定时器回调函数中的this指向window
setTimeout(function () {
console.log(this); // this => window
},5)
7.箭头函数中没有this,它的this取决于其上级作用域
let f=()=>{
console.log(this); // this => window
}
function fn() {
console.log(this);
let f=()=>{
console.log(this); // this => obj
}
f();
}
let obj={name:'a'};
obj.fn=fn;
obj.fn();
8.可以使用Functionn基类原型上的call,apply,bind改变this 的指向
fn.call(obj) => 将fn中的this指向改为obj,立即执行fn
fn.apply(obj) => 将fn 中的this指向改为obj,立即执行fn
fn.bind(obj) => 将fn中的this指向改为obj,并不立即执行而是预执行状态