美文网首页
JavaScript中的this用法

JavaScript中的this用法

作者: liwuwuzhi | 来源:发表于2017-12-01 14:53 被阅读0次

    this在全局中调用时指向的是全局对象。
    this在函数中调用时指向调用函数的对象,调用函数的在不同情况下有

    1.直接调用,此时函数内部的this指向全局对象
    2.作为对象的方法,此时this指向该对象
    3.构造函数,此时this指向构造的实例对象
    4.call/apply改变this指向
    
    

    this是Javascript语言的一个关键字。
    它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。比如,

      function test(){
        this.x = 1;
      }
    

    随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象。
    下面分四种情况,详细讨论this的用法。

    情况一:纯粹的函数调用

    这是函数的最通常用法,属于全局性调用,因此this就代表全局对象global/window(在浏览器中全局对象即顶层对象指的是window,在nodejs中全局对象指的是global)。
    请看下面这段代码,它的运行结果是1。

      function test(){
        this.x = 1;
        alert(this.x);
        alert(this === window);
      test(); 
        // 1
        //true
    

    为了证明this就是全局对象,我对代码做一些改变:

      var x = 1;
      function test(){
        alert(this.x);
      }
      test(); // 1
    

    运行结果还是1。再变一下:

      var x = 1;
      function test(){
        this.x = 0;
      }
      test();
      alert(x); //0
    

    当调用函数test()后,执行this.x 语句,而这里的this.x指向的是全局的x,所以全局的x=1在这个时候变成x=0,所以在最后alert(x)的时候数据0。
    从这里可以看出函数里的 this.x 指的是全局变量x里吧。

    那如果是带有参数的函数呢?再来看看下面的例子:

    var a = 20;
    function fun(a){
        this.a = 1;
        console.log(a);
        console.log(this.a);
    };
    fun(10); 
    //10
    //1
    

    当函数带有参数时,this依旧指向全局的变量,与参数没有任何关系,上面的写法就类似于下面的这种写法。

    var a = 20;
    function fun(b){
        this.a = 1;
        console.log(b);
        console.log(this.a);
    };
    fun(10); 
    //10
    //1
    

    如果把this.a改成this.b呢?那this.b指向的是全局的变量还是函数里面的变量呢?

    var a = 20;
    function fun(b){
        this.b = 1;            //没有用var 相当于定义了一个全局变量b,并赋值为1
        console.log(b);        //10 打印出传入的参数b
        console.log(this.b);   //1  打印出全局变量b
    };
    fun(10);
    console.log(b); //1 打印出全局变量b
    

    JavaScript里规定,全局函数里没有用var定义的的变量是全局变量,所以这里的this.b就相当于定义了一个全局的变量b,所以在最后能打印出变量b

    现在你能看懂下面两个函数了吧

    var a = 20;
    function fun(a){
        this.a = 1;
        console.log(a)
    };
    console.log(a);//20 没有执行this.a=1 语句时,全局变量a依旧为20
    fun(10);//10
    
    var a = 20;
    function fun(a){
        this.a = 1;
        console.log(a)
    };
    fun(10);//10
    console.log(a);//1 执行this.a=1 语句后,全局变量a变为1
    

    情况二:作为对象方法的调用

    函数还可以作为某个对象的方法调用,这时this就指这个上级对象。

      function test(){
        alert(this.x);
      }
      var o = {};
      o.x = 1;
      o.m = test;
      o.m(); // 1
    

    或者用对象字面量来创建方法是好理解些,但都是一个意思

    var pet = {
        words : 'my dear',
        speak : function(){
            console.log(this.words);   //my dear
            console.log(this === pet); //true
        }
    }
    
    pet.speak();
    

    情况三 作为构造函数调用

    所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。

      function test(){
        this.x = 1;
      }
      var o = new test();
      alert(o.x); // 1
    

    运行结果为1。为了表明这时this不是全局对象,我对代码做一些改变:

      var x = 2;
      function test(){
        this.x = 1;
      }
      var o = new test();
      alert(x); //2
    

    运行结果为2,表明全局变量x的值根本没变。
    再来看一个在实际应用中的例子

    function Pet(words){
        this.words = words;
    
        this.speak = function(){
            console.log(this.words);
            console.log(this)
        }
    }
    
    var cat = new Pet('Miao');
    cat.speak();
    //当nwe了一个实例对象cat后,cat拥有了自己的word属性和speak方法,而cat.speak()调用时this指的的是cat对象自己
    // Miao
    //Pet { words: 'Miao', speak: [Function] }
    

    情况四 apply、call调用

    apply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。因此,this指的就是这第一个参数。
      var x = 0;
      function test(){
        alert(this.x);
      }
      var o={};
      o.x = 1;
      o.m = test;
      o.m.apply(); //0
    apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。
    如果把最后一行代码修改为
      o.m.apply(o); //1
    运行结果就变成了1,证明了这时this代表的是对象o。

    apply有两种实际的应用场景:
    1.在对象中--调用时才改变this指向,如上例子,也许下面的例子好理解些

    var pet = {
        words : 'my dear',
        speak : function(say){
            console.log(say + ' ' +this.words)
        }
    }
    
    pet.speak('hello');//hello my dear
    
    //利用apple调用时改变this的指向
    var dog = {
        words :'wang'
    }
    pet.speak.call(dog,'hello');//hello wang
    pet.speak('hello')//hello my dear
    

    2.实现继承时的构造函数--定义时改变this指向

    function Pets(words,sex){
        this.words = words;
        this.sex = sex;
        this.speak = function(){
            console.log(this.words + ' ' + this.sex)
        }
    }
    
    function Dog(words,sex){
        //Pets.call(this, words, sex);
        //Pets.apply(this,[words, sex])
        Pets.apply(this,arguments)
    }
    
    var dog  = new Dog('wang','girl')
    dog.speak();//wang,girl
    



    一些我们会分不清的this指向的情况

    var name = "The Window";
    var object = {
     name : "My Object",
     getName: function(){
     return this.name;
     }
    }; 
    object.getName(); //"My Object"
    

    这里的 getName()方法只简单地返回 this.name 的值,而调用的对象是object,所以返回“My Object”。如果放回里面是个闭包呢?看下面代码:

    var name = "The Window";
    var object = {
       name : "My Object",
       getNameFunc : function(){
           return function(){
               return this.name;
           };
       }
    };
    alert(object.getNameFunc()()); //"The Window"(在非严格模式下)
    

    要如何解决这个问题?

    var name = "The Window";
    var object = {
       name : "My Object",
       getNameFunc : function(){
           var that = this;//把this赋值给that
           return function(){
               return that.name;
           };
       }
    };
    alert(object.getNameFunc()()); //"The Object"
    

    把this赋值给that,看这样就解决了

    在JavaScript事件中也常常出现这种情况,看下面代码

    var box = document.getElementById('box');
    box.onclick = function(){
        console.log(this.id);//box
        function fun2(){
            console.log(this.id);//小胖
            //fun2()里没有id,所以找了最外层作用域的id
        };
        fun2();
    }
    

    对于这个问题我们的解决方法也是一样的,如下

    var id = '小胖';
    var box = document.getElementById('box');
    box.onclick = function(){
        console.log(this.id);//box
            
            var that = this;
        function fun2(){
            console.log(tha.id);//小胖
        };
        fun2();
    }
    

    参考资料:
    1.《JavaScript的this用法》--阮一峰

    相关文章

      网友评论

          本文标题:JavaScript中的this用法

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