JS中精选this关键字的指向规律你记住了吗

  1.首先要明确:
          谁最终调用函数,this指向谁
          this指向的永远只可能是对象!!!!!
         this指向谁永远不取决于this写在哪,而取决于函数在哪里调用!
         this指向的对象,我们称之为函数的上下文context,也叫做函数的调用者是谁!
  2.this指向的规律(与函数调用的方式息息相关)
  this指向的情况取决于函数调用的方式有哪些(总结如下):
      2.1.通过函数名()直接调用--this 指向window;                     
         function func(){
            console.log(this);
             }
  func();

      2.2.通过对象.函数名()调用的--this指向这个对象

                狭义对象: this指向--obj    

                  var obj={
                         name:"obj",
                         func1:func
                         };
                   obj.func1();

 

                 广义对象: this指向--div

 document.getElementById("div").onclick=function(){
      this.style.backgroundColor="red";
      }

    2.3. this指向——数组arr

var arr=[func,1,2,3];
     arr[0]();

    2.4.函数作为window内置函数的回调函数调用,this指向window setInterval,setTimout等

setInterval(func,1000);         
   setTimeout(func,1000)
   2.5.函数作为构造函数,用new关键字调用时:this指向新定义的对象obj
    var obj=new func();

  2.6.  通过call、apply、bind调用,this指向我们规定的对象。

  Func.call(obj,参数一,参数2,参数3.。。。)

  Func.allply(obj,[ 参数一,参数2,参数3.。。。])

   Func.bind(obj)( 参数一,参数2,参数3)   var f = func.bind(obj).   f(…….);

    小试牛刀:
var fullname = 'John Doe';
        var obj = {
           fullname: 'Colin Ihrig',
           prop: {
              fullname: 'Aurelio De Rosa',
              getFullname: function() {
                 return this.fullname;
              }
           }
        };
        console.log(obj.prop.getFullname()); // Aurelio De Rosa
        //函数最终调用者:obj.prop  this--->obj.prop
         
        var test = obj.prop.getFullname;
         
        console.log(test());  // John Doe
        // 函数最终调用者: 函数() window  this-->window

 

posted on 2017-05-13 10:08  海*星  阅读(474)  评论(0编辑  收藏  举报