this 的指向会被分为几种情况。
全局环境下
console.log(this); // window
普通函数中的 this 指向全局
function fn(){
console.log(this); // 指向window
}
fn();
即使是嵌套的函数, this 也是指向全局对象
function fn() {
function inner(){
console.log(this); // 指向window
}
a();
};
fn();
通过对象调用, this 指向该对象
let obj = {
name: "陈涛",
fn(){
console.log(this); // 整个 obj对象
}
}
obj.fn();
function fn() {
console.log(this);
}
fn(); // 指向window
const obj = { name: "陈涛" };
obj.tolk = fn;
obj.tolk(); // {name: "陈涛"}
事件监听器中的 this,指向事件源
btn.onclick = function(){
console.log(this);
}
构造函数中的 this,指向 new 出来的实例对象
function fn(name) {
this.name = name;
console.log(this); // {name:"陈涛"}
}
let obj = new fn("陈涛");