• 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
  • 相关阅读:
    常数时间国密算法
    A Guide to the Go Garbage Collector
    并发控制 互斥
    词典遍历顺序
    max size of IPv4 & IPv6 packet 包大小
    BufferOverflow Attacks
    unsigned 是表示无符号数据类型,
    回溯 递归 的回退状态
    抖音平台多产物代码隔离技术的实践与探索
    依赖注入 开发效率
  • 原文地址:https://www.cnblogs.com/waj6511988/p/6848213.html
Copyright © 2020-2023  润新知