this详解

作者: jweboy_biu | 来源:发表于2018-01-15 23:29 被阅读0次

含义

  • 既不指向函数本身,也不指向函数的词法作用域。
  • 运行时动态绑定,并不是编写绑定,上下文取决于函数调用的各种条件。
  • 指向取决于函数被调用的位置,也是在函数调用时候发生绑定。

解析

调用栈(可以比拟成函数调用链)

  • 指到达当前执行位置所调用的所有函数
  • so调用位置(函数被调用的位置,而不是声明位置)就是当前执行函数的前一个调用

function foo() {
    // 当前调用栈 => foo
    // 当前调用位置 => global全局作用域
    
    console.log('foo')
    bar() // bar调用位置
}

function bar() {
    // 当前调用栈 => foo -> bar
    // 当前调用位置 foo
    
    console.log('bar')
}

绑定规则

  • 默认 => 独立函数调用

    • this默认绑定,指向全局对象
  • 隐式 => 是否存在上下文 / 被某个对象拥有或包含

    • 当函数引用存在上下文,this会被隐式绑定到这个上下文对象
    • 对象属性引用链只对调用位置的(上一层 / 最后一层)有效
    function foo() {
        return this.a
    }
    
    const obj = {
        a: 'hello',
        foo, // 函数引用,当前上下文是obj
    }
    
    obj.foo()
        
    
  • 显式绑定 => call, apply, bind

    • 硬绑定
    function foo() {
        return this.a
    }
    
    const obj = {
        a: 'hello
    }
    
    const bar = function() {
        foo.call(obj) // 显式的强制绑定
    }
    setTimeout(bar, 300)
    bar.call(window) // 2 => 硬绑定之后this无法再修改
    
    
  • new绑定 => 构造函数调用,实际上并不存在“构造函数”,是对函数的“构造调用”

    • 创建(构造)一个全新的对象
    • 这个对象会被执行[[Prototype]]连接
    • 这个对象会绑定到函数调用的this
    • 如果函数没有返回对象,直接返回这个新对象

注意点


隐式绑定会丢失绑定对象,从而应用默认绑定,分别有以下两种情况。

  1. 函数别名 => 引用函数本身,so默认绑定

    function foo() {
        return this.a
    }
    
    const obj = {
        a: 'hello',
        foo, // 函数引用,当前上下文是obj
    }
    
    const a = 'on no, this is global'
    const bar = obj.foo // 函数别名
    bar() // 'on no, this is global'
        
    
  2. 参数传递 => 隐式赋值,同上

    function foo() {
        return this.a
    }
    
    function doFoo(fn) {
        
        fn() // fn => foo
    }
    
    const obj = {
        a: 'hello',
        foo, // 函数引用,当前上下文是obj
    }
    
    const a = 'on no, this is global'
    doFoo(obj.foo) // 'on no, this is global'
        
    

优先级

  • 显式 > 隐式

  • new > 隐式

  • new可以修改显式的this

        function foo(some) {
            this.a = some
        }
        
        const obj = {}
        
        const bar =  foo.bind(obj)
        bar(2)
        console.log(obj.a) // 2
        
        const baz = new bar(3)
        console.log(obj.a) // 2
        console.log(baz.a) // 3 => new 修改了this绑定
    
  • new中使用硬绑定 => 函数柯理化

        function foo(a, b) {
            this.value = a + b
        }
        
        const bar = foo.bind(null, 'hello ') //这里 this不指定,new时会修改
        const baz = new bar('world')
        baz.value // 'hello world'
    

相关文章

网友评论

    本文标题:this详解

    本文链接:https://www.haomeiwen.com/subject/atsjoxtx.html