• 作为普通函数
    • 使用call,apply,bind
    • 作为对象方法被调用
    • 在class方法中调用
    • 箭头函数

    this是在函数执行的时候确认的,不是在函数定义的时候确认的

    1. function fn1() {
    2. console.log(this)
    3. }
    4. fn1() // windou
    5. fn1.call({x: 100}) // {x: 100} //call 直接执行
    6. const fn2 = fn1.bind({x : 200}) //bind 会返回一个新的函数执行
    7. fn2() // {x: 200}
    1. const zhangsan = {
    2. name: '张三',
    3. sayHi(){
    4. //this 指向当前对象
    5. console.log(this)
    6. }
    7. wait() {
    8. setTimeout(function() {
    9. // this === windou
    10. console.log(this)
    11. })
    12. }
    13. }
    1. const zhangsan = {
    2. name: '张三',
    3. sayHi(){
    4. //this 指向当前对象
    5. console.log(this)
    6. }
    7. waitAgain() {
    8. setTimeout(() => {
    9. //this 指向当前对象
    10. console.log(this)
    11. })
    12. }
    13. }
    1. class People {
    2. constructor(name) {
    3. this.name = name
    4. },
    5. sayHi(){
    6. console.log(this)
    7. }
    8. }
    9. const zhangsan = new People('张三')
    10. zhangsan.sayHi() //张三对象

    call.png