(function(){ var resources = document.getElementById('resources'); resources.addEventListener('click',handler,false); functionhandler(e){ var x = e.target; // get the link tha if(x.nodeName.toLowerCase() === 'a'){ alert('Event delegation:' + x); e.preventDefault(); } }; })();
var name = 'Chris'; var age = '34'; var status = 'single'; functioncreateMember(){ // [...] } functiongetMemberDetails(){ // [...] }
为了避免这一问题,你可以使用匿名函数:
1 2 3 4 5 6 7 8 9 10 11
var myApplication = function(){ var name = 'Chris'; var age = '34'; var status = 'single'; functioncreateMember(){ // [...] } functiongetMemberDetails(){ // [...] } }();
如果这个函数不会被调用,可以更直接为:
1 2 3 4 5 6 7 8 9 10 11
(function(){ var name = 'Chris'; var age = '34'; var status = 'single'; functioncreateMember(){ // [...] } functiongetMemberDetails(){ // [...] } })();
如果要访问其中的对象或函数,可以:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var myApplication = function(){ var name = 'Chris'; var age = '34'; var status = 'single'; return{ createMember:function(){ // […] }, getMemberDetails:function(){ // […] } } }(); // myApplication.createMember() and // myApplication.getMemberDetails() now works.
这就是所谓 Module 模式或单例模式(Singleton),该模式为 Douglas Crockford 所推崇,并被大量应用在 Yahoo User Interface Library YUI。