zoukankan      html  css  js  c++  java
  • 关于 this对象 指向问题

     this 定义:this是包含它的函数作为方法被调用时所属的对象。(1,this所在的函数。2,此函数作为方法被调用。3,this等于调用此函数的对象)

    this 对象在运行时基于函数的执行环境绑定的。在全局环境中this等于window,当函数作为某个对象的方法调用时,this等于那个对象。所以说,this的指向完全

    取决于函数的调用方式。

    1》函数的四种调用方式

      1.函数调用模式

    function fn() {console.log(this)}
    fn(); //window

    this是全局对象(window)

    2.方法模式

    var obj = {
       a: function() {console.log(this)}
    };

    obj.a(); //this指向obj

    this是当前调用方法的对象

    3. 构造器模式(constructor)

      function Fn() {this}//this指向p
       var p = new Fn();

    function Point(x, y){ 
        this.x = x; 
        this.y = y; 
     }

     this指向新创建出来的对象

     

    4上下文模式 (通过call或apply改变函数执行环境的情况下 ,this 也会指向其他对象)

         1.函数名.apply(this指向的对象,[参数1, 参数2, ...])    

          function foo() {console.log( this );}
            foo.apply();//this指向window
            foo.apply( null );//this指向window
             var o = { name: 'aaa' };
           foo.apply( o );//this指向o,用o调用foo  

    2. 函数名.call(this指向的对象,参1,参2...);

           call和apply的区别  apply的第二个参数是数组形式,call第二个参数是单个参数分开传入

       例子:

     

     function Point(x, y){ 
        this.x = x; 
        this.y = y; 
        this.moveTo = function(x, y){ 
            this.x = x; 
            this.y = y; 
        } 
     } 
    
     var p1 = new Point(0, 0); 
     var p2 = {
    x: 0,
    y: 0
    }; p1.moveTo(1, 1); p1.moveTo.apply(p2, [10, 10]);
    我们看到使用 apply 可以将 p1 的方法应用到 p2 上,这时候 this 也被绑定到对象 p2 上

     

    2》在闭包中如果把外部作用域中的this对象保存在一个闭包能够访问到的变量里面。就可以让闭包访问该对象。

       var name='jim';var obj={
        name:'tom',
        getName:function(){
            var that=this;
            return function(){
                return that. name;
            }
        }
    }
    alert(obj.getName()())//'tom'
     that是在包含函数中特意声明的变量  它指向的obj

    3》语法的细微变化 也会引起this的变化

      var name='jim';
    var obj={
        name:'tom',
        getName:function(){
                return this. name;
        }
    }
    obj.getName() // tom
    (obj.getName=obj.getName)()//jim
         第二个打印进行了一次赋值操作   所谓赋值
        如果a=b=function(){} 先将函数赋值给b 再将函数赋值给a

      在例子中 (a=b)它是赋值后的结果 也就是函数本身 调用函数本身 则此时this指向window.

     

  • 相关阅读:
    .NetCore Grpc 客服端 工厂模式配置授权
    DOCKER 拉取 dotnet 镜像太慢 docker pull mcr.microsoft.com too slow
    Introducing .NET 5
    VSCode 出现错误 System.IO.IOException: The configured user limit (128) on the number of inotify instances has been reached.
    Omnisharp VsCode Attaching to remote processes
    zookeeper3.5.5 centos7 完全分布式 搭建随记
    Hadoop2.7.7 centos7 完全分布式 配置与问题随记
    MySQL索引 索引分类 最左前缀原则 覆盖索引 索引下推 联合索引顺序
    SQL基础随记3 范式 键
    MySQL调优 优化需要考虑哪些方面
  • 原文地址:https://www.cnblogs.com/wyan20/p/5397390.html
Copyright © 2011-2022 走看看