函数体外访问问题

 

(function(){

function testA(){

alert('testA')

};

})();

testA();

怎么能访问到:

testA();

(function(){
function testA(){
alert('testA')
};

window.testA = testA;

})();

testA();//可以调用

(function(){
function testA(){
alert('testA')
};

testABC = testA;

})();

testABC();//可以调用

(function(){

function testA(){

    alert('testA')

};
    testABC = testA; //前边不加var 将表示为全局

})();

testABC();

(function(){

function testA(){

    alert('testA')

};
    window.testA = testA; //注册到window上

})();

testA();

这两种方式都是不好的,因为$(function(){}) 是在页面加载完执行的。 可能执行到外边的testA $(function(){}) 还没执行;

直接 把testA放在外部:
function testA(){
alert('testA')
};

$(function(){

})();

testA();

[code="java"]var s ={};

(function(){

s.testA = function(){

    alert('testA')

};

})();

s.testA();[/code]

此问题和:
[url]http://www.iteye.com/problems/88088[/url]类似
[code="html"]<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">



Insert title here

<br> $(function(){<br> alert(&quot;1&quot;);<br> function demo()<br> {<br> alert(&quot;demo&quot;);<br> }<br> window.somefun=function(){<br> alert(&quot;外面 也要调用&quot;);<br> }</p> <pre><code> }); function test1() { somefun();//或者 window.somefun(); } &lt;/script&gt; </code></pre> <p></head><br> <body><br> <input onClick="test1()" type="button" value="测试" /><br> <input onClick="somefun()" type="button" value="测试" /><br> </body><br> </html><br> [/code]</p>

(function(){
function testA(){
alert('testA')
};
})();

这么写 testA函数只是一个局部变量 只有在(function(){ 内部})(); 能访问 ,外部访问不了

一种解决方式就是我写的下面的形式:
[code="java"]var s ={};

(function(){

s.testA = function(){   

    alert('testA')   

};   

})();

s.testA(); [/code]