this
this详解
一、为什么要有this
原因1:不用每次都传上下文(context)
function uppercaseName() {
return this.name.toUpperCase();
}
function sayHi() {
console.log(`Hello, I am ${uppercaseName.call(this)}, and ${this.age} years old.`);
}
let Tom = {
name: 'tom',
age: 8
};
let Jerry = {
name: 'jerry',
age: 9
};
sayHi.call(Tom);
sayHi.call(Jerry);原因2:没有this,class无法实现
二、this指向谁
1、默认:this -> 全局变量(非严格模式)/上下文
2、隐式:this -> 调用对象
3、显式:this -> 指定对象
4、new:this -> 新对象
三、破解this的困局
Last updated