this
this 的指向会被分为几种情况。
1. 全局环境下
console.log(this); // window
2. 普通函数中的 this 指向全局
严格模式下指向 undefined。
function fn(){
console.log(this); // window
}
fn();
即使是嵌套的函数, this 也是指向全局对象
function outer() {
function inner(){
console.log(this); // window
}
inner();
};
outer();
3. 通过对象调用, this 指向该对象
let obj = {
name: "zhangsan",
talk(){
console.log(this); // 整个 obj
}
}
obj.talk();
function foo() {
console.log(this);
}
foo(); // window
const obj = { name: "zhangsan" };
obj.talk = foo;
obj.talk(); // {name: "zhangsan"}
4. 事件监听器中的 this,指向事件源
btn.onclick = function(){
console.log(this); // <input type="button"