《你不知道的JavaScript(上卷)》笔记:关于this

  1. this提供了一种更优雅的方式来隐式“传递”一个对象引用,因此可以将API设计得更加简洁并且易于复用。

    function identify() {
        return this.name.toUpperCase();
    }
    function speak() {
        var greeting = "Hello, I'm " + identify.call( this );
        console.log( greeting );
    }
    var me = {
        name: "Kyle"
    };
    var you = {
        name: "Reader"
    };
    
    identify.call(me);
    identify.call(you);
    
    speak.call(me);
    speek.call(you);

    对比:

    functon identify(context) {
        return context.name.toUpperCase();
    }
    function speak(context) {
        var greeting = "Hello, I'm " + identify(context);
        console.log( greeting);
    }
    identify(you);
    speek(me);
  2. this 是在运行时进行绑定的,并不是在编写时绑定,它的上下文取决于函数调用时的各种条件。this 的绑定和函数声明的位置没有任何关系,只取决于函数的调用方式。

  3. this实际上是在函数被调用时发生的绑定,它指向什么完全取决于函数在哪里被调用。

猜你喜欢

转载自blog.csdn.net/wuweitiandian/article/details/79452039