惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Microsoft Security Blog
Microsoft Security Blog
J
Java Code Geeks
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
N
Netflix TechBlog - Medium
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园_首页
宝玉的分享
宝玉的分享
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
Hugging Face - Blog
Hugging Face - Blog
量子位
Blog — PlanetScale
Blog — PlanetScale
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
阮一峰的网络日志
阮一峰的网络日志
D
Docker
罗磊的独立博客
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
云风的 BLOG
云风的 BLOG
IT之家
IT之家
MyScale Blog
MyScale Blog
Microsoft Azure Blog
Microsoft Azure Blog

博客园 - Tobin

41岁的大龄程序员,苟着苟着,要为以后做打算了 UC_Center整合单点登录后远程注册不激活问题的解决办法 AspExe - a small ASP.NET compiler and executor for document generation 在as3中Embed(绑定)flash动画元素 - Tobin - 博客园 Embedding Resources with AS3 Configure the max limit for concurrent TCP connections [转]翻译:使用.net3.5的缓存池和SocketAsyncEventArgs类创建socket服务器 强制将IE,Chrome设置为指定兼容模式来解析(转) - Tobin - 博客园 工商银行,千万别用,转账不成功一样收手续费 MySQL vs NoSQL 效率与成本之争(转) 使用ASP.NET Global.asax 文件(转) [MySql识记]create utf8 database - Tobin npgsql连接postgresql数据库 由浅到深了解JavaScript类[转过来的收藏] 哪个美女最漂亮,自己写的js图片自适应切换 javascript操作cookie实例 [图解] 你不知道的 JavaScript - “this”(转) 对与list<>泛型的一些操作方法 关于游戏开发中的A*/A-star的寻路算法的问题
javascript改变this指针
Tobin · 2008-07-15 · via 博客园 - Tobin

今天写代码时遇到一个问题,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到底是做啥子用的,只能先记下来,以后慢慢理解!