this的取值是在执行的地方确定的,不是定义的时候
function fn1() { console.log(this) } fn1() // window fn1.call({ x: 100 }) // { x: 100 } const fn2 = fn1.bind({ x: 200 }) fn2() // { x: 200 }
const zhang = { name: ‘zz‘, sayHi() { // this 即当前对象 console.log(this) }, wait() { setTimeout(function() { // this === window console.log(this) }) } }
const zhang1 = { name: ‘zz‘, sayHi() { // this 即当前对象 console.log(this) }, wait() { setTimeout(() => { // 箭头函数中的this 永远指向上级作用域的this // this 即当前对象 console.log(this) }) } }
class People { constructor(name) { this.name = name } eat() { console.log(`eat: 姓名 ${this.name}`) } } const xiaoming = new People(‘小明‘) // this === xiaoming 对象
原文:https://www.cnblogs.com/dahai5566/p/13507925.html