迷一样的 this

各种 this 常常令人非常迷惑,至今只能理解简单的情况,对于复杂的情况 this 传来传去,绑来绑去。。。还是会晕,不能透彻的理解。

this is neither a reference to the function itself, nor is it a reference to the function's lexical scope.
this is actually a binding that is made when a function is invoked, and what it references is determined entirely by the call-site where the function is called.

this 既不指向函数,也不指向函数的 scope, 而是在函数执行时动态绑定到所处的上下文。

this 到底绑定到什么,有 4 种基本的情况:

Default Binding

function foo() {
    console.log( this.a );
}

var a = 2;

foo(); // 2

this 默认会绑定到 global 对象

function foo() {
    "use strict";

    console.log( this.a );
}

var a = 2;

foo(); // TypeError: `this` is `undefined`

只有在非严格模式下才允许 this 绑定到 global, 严格模式下不允许绑定到 global

Implicit Binding 隐式绑定

function foo() {
    console.log( this.a );
}

var obj = {
    a: 2,
    foo: foo
};

obj.foo(); // 2

用一个对象 obj 去调用函数,这时 this 就绑定到函数所在的对象

Explicit Binding 显示绑定

function foo() {
    console.log( this.a );
}

var obj = {
    a: 2
};

foo.call( obj ); // 2

通过 call 或 apply 显示调用一个函数并传递一个对象进去,这时 this 就绑定到传入的对象上。这种情况最好理解。

new Binding

function foo(a) {
    this.a = a;
}

var bar = new foo( 2 );
console.log( bar.a ); // 2

当用 new 调用一个函数时主要做了下面4件事

  1. a brand new object is created
  2. the newly constructed object is [[Prototype]]-linked
  3. the newly constructed object is set as the this binding for that function call
  4. unless the function returns its own alternate object, the new-invoked function call will automatically return the newly constructed object.

当用 new 调用一个函数时,底层默认会新建一个对象,this 会绑定到这个新建的对象上。默认函数会返回这个新建的对象,当然也可以返回其它的对象。

Determining the this binding for an executing function requires finding the direct call-site of that function. Once examined, four rules can be applied to the call-site, in this order of precedence:

  1. Called with new? Use the newly constructed object.

  2. Called with call or apply (or bind)? Use the specified object.

  3. Called with a context object owning the call? Use that context object.

  4. Default: undefined in strict mode, global object otherwise.

总结下来就是找到函数调用点,依次看看是否符合以上 4 条规则

  1. 如果用 new 调用, this 绑定到函数新建的对象上
  2. 显示调用直接绑定到传入的对象上
  3. 通过对象调用,绑定到函数所在的对象上
  4. 默认绑定到 global 对象

Lexical this

function foo() {
    // return an arrow function
    return () => {
        // `this` here is lexically adopted from `foo()`
        console.log( this.a );
    };
}
var obj1 = {
    a:100
};
var a = 200;
foo.call(obj1)(); // 100

arrow-functions adopt the this binding from the enclosing (function or global) scope.

ES6 的 => 函数中的 this 会绑定到它所在的 scope 的 this。这里就是 foo 的 this。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容