前言:我喜欢在js中更改函数执行上下文的指向,也成为this的指向。
那么this在各种环境下this,指向的是谁。小编给大家总结了以下几条结论
- 全局环境下
console.log(this); // window
- 普通函数
function foo() {
console.log(this); // window
}
foo();
// 嵌套也一样
function bar() {
function foo() {
console.log(this); // window
}
foo();
}
bar();
- 普通对象,谁调用我就指向谁
let obj = {
name: "zhangsan",
say() {
console.log(this.name);
}
}
obj.say(); // zhangsan
let cc = obj; // 把obj开辟一个新的地址给cc
cc.name = "lisi"; // 原本cc有name的键值,这一句重新给赋值了
cc.say(); // lisi // cc调用say的方法,因为this的指向是cc,找cc.name。所以 打印的是lisi
- 监听器中的this,指向事件源(绑定事件的元素节点)
注:区分this和event.target
let ele = document.querySelector(".ele");
ele.addEventListener("click",function(event){
console.log(this); // 事件源
console.log(event.target); // 触发事件的某元素
})
- 构造函数的this,new出来的那个实例化对象
function Foo(name){
this.name = name;
console.log(this);
}
let obj = new Foo("zhangsan");
- 箭头函数中的this
注:箭头函数没有自己的this,使用所处的环境中this || 继承环境中的this || this指向取决于当前声明的环境
let obj = {
name:"zhangsan",
talk:()=>{
console.log(this)
}
}
obj.talk(); // window
//箭头函数没有自己的this,对象无法生成上下文,只有全局上下文,所以箭头函数使用全局的this
document.addEventListener("click", function() {
let foo = item => console.log(this);
foo(); //document
});