首页 > 其他 > 详细

this

时间:2020-08-15 13:29:30      阅读:51      评论:0      收藏:0      [点我收藏+]

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 对象

 

this

原文:https://www.cnblogs.com/dahai5566/p/13507925.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!