关于自由变量和this的取值

JavaScript this 关键字

面向对象语言中 this 表示当前对象的一个引用。

但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。

    • 在方法中,this 表示该方法所属的对象。
    • 如果单独使用,this 表示全局对象。
    • 在函数中,this 表示全局对象。
    • 在函数中,在严格模式下,this 是未定义的(undefined)。
    • 在事件中,this 表示接收事件的元素。
    • 类似 call() 和 apply() 方法可以将 this 引用到任何对象。

 

 

 

  1. 自由变量取值由函数定义时决定
  2. 在函数中,this的取值由函数执行时决定,箭头函数的this永远是其上一级的作用域this的取值

 

/*
自由变量
*/
let a = 100 function retrunA() { console.log(a) } function retrunB() { let a = 200 retrunA() }
retrunB()
//结果a=100

/*
this的指向
*/
this.b = 1 function A() { const bb = new B() console.log('bb.b:' + bb.b) } function B() { console.log(this.b) setTimeout(() => { console.log('箭头函数:', this.b) }, 100); setTimeout(function() { console.log('setTimeout:', this.b) }, 5000); this.b = 2 } A() console.log('this:', this)

/*
执行过程分析:
    全局执行this.b = 1
    全局定义函数A()
    全局定义函数B()
    全局执行A()
        A中执行B()
            B中执行 console.log(this.b),this是指向B --》 打印1: undefined
            B中执行 setTimeout(() => {console.log('箭头函数:', this.b)}, 100),回调中this是指向B --》 web api入栈此条,待触发执行() => {console.log('箭头函数:', this.b)}
            B中执行 setTimeout(function() {console.log('setTimeout:', this.b)}, 500),回调中this是指向定时器Timeout--》 web api入栈此条,待触发执行function() {console.log('setTimeout:', this.b)}
            B中执行 this.b = 2,b:{b:2}
         A中执行console.log('bb.b:' + bb.b), bb是指向B--》打印2: 'bb.b: 2'
    全局执行 console.log('this', this) --》打印3:'this:{ b: 1 }'
    100 ms后执行console.log(this.b), this是指向B--》打印4: '箭头函数: 2'
    100 ms后执行func() --》执行console.log(this.b), this是指向定时器Timeout--》打印5: 'setTimeout: undefined'

执行结果:
 undefined
 bb.b: 2
 this:{ b: 1 }
 箭头函数: 2
 setTimeout: undefined

 */

  

posted @ 2020-10-16 12:33  baixinL  阅读(227)  评论(0编辑  收藏  举报