zoukankan      html  css  js  c++  java
  • javascript改变this指针

    今天写代码时遇到一个问题,this指针的问题,先把代码贴上
    <script type="text/javascript">
    window.onload
    =function()
    {
        
    var m=new main('aaaa');
        m.run();
    }

    var main=function(param)
    {
         
    this.param=param;

         
    this.run=function()
         
    {
         setTimeout(
    this.Change,3000);
         }


         
    this.Change=function()
         
    {
         alert(
    this.param);
         }

    }

    </script>
    这个代码看起来很清晰,但是会报错,原因我想大概就是在隔了三秒执行Change方法时找不到this.param,this.Change的this就指向了window,不是实例m了,整了半天没有整明白,没办法只好上网求助,结果有高手给除了解决方法,修改this指针。再来看新代码:
        <script type="text/javascript">
    window.onload
    =function()
    {
        
    var m=new main('aaaa');
        m.run();
    }

    var main=function(param)
    {
         
    this.param=param;
         
    this.run=function()
         
    {
         
    var self=this;
         setTimeout(self.Change.setThis(self),
    3000);
         }

         
    this.Change=function()
         
    {
         alert(
    this.param);
         }

         Function.prototype.setThis 
    = function(object) 
         

            
    var __method = this
            
    return function() 
            

            __method.apply(object, arguments); 
            }
     ;
         }
    ;
    }

    </script>

    其中添加了一段修改指正的代码,修改指针代码:
     Function.prototype.setThis = function(object) 
         { 
            var __method = this; 
            return function() 
            { 
            __method.apply(object, arguments); 
            } ;
         };
    使用的时候要定义一个变量self=this; 用self来调用。最主要的是不理解apply到底是做啥子用的,只能先记下来,以后慢慢理解!


                                                       第八宗罪Tobin

  • 相关阅读:
    SimpleRetryTemplateSupplier
    Atcoder Grand Contest 013 E Placing Squares(组合意义转化+矩阵快速幂/代数推导,思维题)
    Atcoder Grand Contest 033 D Complexity(dp)
    Vue案例之计数器
    Redis数据类型之List列表类型
    Redis数据类型之Hash哈希类型
    Vue之vfor列表展示
    Vue初体验
    RedisDesktopManager本地连接云服务器上的Redis
    Redis数据类型之ZSet有序集合类型
  • 原文地址:https://www.cnblogs.com/tobin/p/1243514.html
Copyright © 2011-2022 走看看