javascript的this的应用场景

先记住了一句话

this取什么值是在函数执行时候确定的,而不是在函数定义时候确定的!

场景一:作为普通函数

function fn(){
    console.log(this)
}

场景二:作为call apply bind

fn.call({ x: 100 }) //this指向{ x : 100 }

const f2 = fn.bind({ x:200 })
f2() // this指向{x: 200}

场景三:作为对象方法被调用

注意setTimeout的用法

ES5:

const zhangsan = {
  name: '张三',
  sayHi() {
    console.log(this)
  },
  wait() {
    setTimeout(function(){
      // this === window
      console.log(this)
    }, 100)
  }
}

ES6:

const zhangsan = {
  name: '张三',
  sayHi() {
    console.log(this)
  },
  wait() {
    setTimeout(() => {
      // 这个this是指向zhangsan这个对象的
      console.log(this)
    }, 100);
  }
}

场景四:在class中被调用

class People {
  constructor(name){
    this.name = name
    this.age = 100
  }
  sayHi() {
    console.log(this)
  }
}
const lisi = new People('李四')
lisi.sayHi() //sayHi里面的this是指向lisi对象

场景五:箭头函数

记住一点,在箭头函数中的this是指他{}块级作用域里面的值(如上面场景三里面的)

发布了62 篇原创文章 · 获赞 11 · 访问量 8639

猜你喜欢

转载自blog.csdn.net/qq_38588845/article/details/103171593
今日推荐