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    app

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

 

                 广义对象: this指向--div函数

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

    2.3. this指向——数组arrthis

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

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

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

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

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

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

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

    小试牛刀:
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
相关文章
相关标签/搜索