2013-03-13 83 views
0

這裏的外部調用jQuery的命名空間的功能是代碼從jQuery命名空間

test ('e'); 
function test(e) { 
    test2(e); //undefined 
} 

(function ($) { 
    function test2(e) { 
     alert('test'); 
    } 
}) 

由於一些限制,我有這樣的呼籲。有誰知道?

回答

0

可以,通過聲明test2匿名函數外:

var test2;      //Declare test2 in global 
(function ($) { 
    test2 = function (e) {  //define test2 
     alert('test');   //because test2 was declared in global, 
    };       // it will stay global. 
})(jQuery); 

test('e');      //Call test 

function test(e) { 
    test2(e);     //Since test2 can be access anywhere in your code, 
}        //it is now defined. 

演示:http://jsfiddle.net/DerekL/LEZkt/

+0

最好回答,謝謝 – hkguile 2013-03-13 03:36:34

+0

@hkinterview - 不客氣。 PS:hkinterview,香港慨? – 2013-03-13 03:47:44

+0

系呀,你是香港人? ............. – hkguile 2013-03-13 03:52:54

1

您不能,函數test2已經在閉包中定義,您只能調用該範圍內的函數。在文件

0

綁定事件,觸發它:

function test(e) { 
        var param=1; 
            param2=4; 
        jQuery(document).trigger('mytest2',[param,param2]);  
    } 
(function ($) { 
    $(document).bind('mytest2',test2);  
    function test2(event,param,param2) { 
     alert('test '+param+' '+param2); 
    } 
})(jQuery) 
setTimeout(test,2000); 

http://jsfiddle.net/oceog/CzNKu/