this在不同环境中指向的不一致性可能导致很多难以排查的错误, 特此整理一波this 在不同环境下的指向. 请牢记
this最终指向的是运行时调用该函数的对象
函数中的this
此时 `this=window`
function test(){
let x = 1;
console.log(this.x); //undefined
}
//直接调用
test(); // 调用的是window.test(), this指向window
//赋值调用
let obj={
x:1,
fn:test
}
let fn=obj.fn;
fn();// 调用的是window.fn(), this指向window
对象属性方法中的this
function test(){
let x = 1;
console.log(this.x); //undefined
}
let obj = {
x:2,
fn:function(){
console.log(this.x); // 2 调用的是obj.fn, this指向obj,
setTimeout(test,1000); //调用的是window.setTimeout, test里面this指向window
},
};
obj.fn();
事件绑定与监听中的this
//事件绑定
let btn = document.querySelector("button")
btn.onclick = function () {
console.log(this) // 调用的是btn.onclick, this指向btn
}
//事件监听
var btn = document.querySelector("button")
btn.addEventListener('click', function () {
console.log(this) // 调用的是btn.onclick, this指向btn
})
call apply bind 中的this
- call apply bind 参数
不为空
时,默认将this绑定到第一个参数
对象上 - call apply bind 参数
为空
时,默认将this绑定到全局对象window
上 - call表示强行将this指向第一个参数调用
- apply 表示将参数(数组)
打散
成多个参数, 并强行将this指向第一个参数调用 - bind 表示强行将this指向第一个参数并生成一个新的函数对象返回, 执行返回后的函数才能运行
function test(){
let x = 1;
console.log(this.x); // 2
}
let obj={
x:2,
};
test.call(); //undefined
test.call(obj); //2
test.apply(); //undefined
test.apply(obj); //2
let fn0=test.bind();
fn0(); //undefined
let fn=test.bind(obj);
fn(); //2
setInterval,setTimeout中的this
调用的是window.setInterval
和window.setTimeout
, this必定指向window
function test(){
let x = 1;
console.log(this.x); //undefined
}
let obj = {
x:2,
fn:function(){
setTimeout(test,1000); //调用的是window.setTimeout, this指向window
//此处如何将this指向obj?
// setTimeout(test.bind(this),1000);
// setTimeout(test.bind(obj),1000);
},
};
obj.fn();
setTimeout(test,1000); //调用的是window.setTimeout, this指向window
//此处如何将this指向obj?
// setTimeout(test.bind(obj),1000);
箭头函数中的this
function test(){
let x = 1;
console.log(this.x); //2
return ()=>{
console.log(this.x); //2 箭头函数将this指向当前环境上下文,即this指向test中的this,即obj
}
}
let obj = {
x:2,
fn:test,
fn1:()=>{
console.log(this.x); //undefined 箭头函数将this指向当前环境上下文,即this指向全局环境中的this,即window
}
};
var fn=obj.fn();
fn();
obj.fn1();
new 构造函数中的this
- 当构造函数中
没有return
时, this指向新建的对象并返回新建的对象 - 当构造函数中
return null
时, this指向新建的对象并返回新建的对象 - 当构造函数中
return 对象
时, this指向新建的对象,但返回return 后的对象
function People(){
this.a=1;
this.b=2;
}
let obj=new People();
console.log(obj.a); //1
function People1(){
this.a=1;
this.b=2;
return {}
}
let obj1=new People1();
console.log(obj1.a); //undefined
function People2(){
this.a=1;
this.b=2;
return function(){}
}
let obj2=new People2();
console.log(obj2.a); //undefined
function People3(){
this.a=1;
this.b=2;
return null
}
let obj3=new People3();
console.log(obj3.a); //1
(ps:如有考虑不周或错误之处,请指正。如果有用,请点赞o( ̄▽ ̄)d
)