难以理解的JavaScript变量作用域

Posted on September 17, 2008 by Fdream

在一个iframe中,有这样一段js:

var clear_btn = parent.document.getElementById('clearbtn');
clear_btn.onclick = function () {
    //...
    PSearch.clearResult(); // PSearch这个对象在该页面引用的js文件中,全局变量
    //...
};

当在我的IE 7下的时候居然会out of memory,而在clearResult中并没有干任何事情!在IE 8下的时候,却是找不到PSearch,很诡异……突然想起曾经碰到过类似的问题,于是改成这样:

var clear_btn = parent.document.getElementById('clearbtn');
var ps = PSearch; // PSearch这个对象在该页面引用的js文件中,全局变量
clear_btn.onclick = function () {
    //...
    ps.clearResult();
    //...
};

这下就跑得很好了,一点问题没有……很莫名奇妙……

分享 |
Categories:
Ajax Web
Tags:
Comments:
2 Comments
Views:
1,402 Views

Related Posts

2 Responses to <难以理解的JavaScript变量作用域>

  1. rukey67 says:

    闭包传值问题吧

  2. Fdream says:

    后面那个写法只是多写了一个引用而已,并没有什么特别的意义,很诡异……

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>