function interfaceInit(){
Dialog = (function (){
var now = null;
return {
add : function (id){
alert( id);
},
getNow : function(){
alert(now);
}
}
})();
}
Dialog = (function (){
var now = null;
return {
add : function (id){
alert( id);
},
getNow : function(){
alert(now);
}
}
})();
}
==========var init = new interfaceInit();
init.Dialog.add();
init.Dialog.getNow();类似这样吧。
可以把下面的代码扔到页面中,应该会alert出2.<script>
var Dialog = {};
function interfaceInit(){
var now = null;
Dialog = {
add : function(id){
alert(id);
},
getNow : function(){
alert(now);
}
}
}
var interface = new interfaceInit();(function(){
var dialog = Dialog;
dialog.add(2);
})()
</script>
你自己写的代码有做过测试吗?!To:foolbirdflyfirst
<script>
var Dialog = {};
function interfaceInit(){
var now = null;
Dialog = {
add : function(id){
alert(id);
},
getNow : function(){
alert(now);
}
}
}
var interface = new interfaceInit();(function(){
var dialog = Dialog;
dialog.add(2);
})()
</script>你的代码只是预先将function interfaceInit里面的局部变量Dialog声明成全局变量罢啦。
改成<script>
var Dialog = {};
function interfaceInit(){
var now = null;
Dialog = {
add : function(id){
alert(id);
},
getNow : function(){
alert(now);
}
}
}
interfaceInit();var dialog = Dialog;
dialog.add(2);
</script>
这样子就可以运行。等待高人来解答
我原意是让lz明白
1.(function(){alert(1)})();//定义一个匿名函数,然后马上执行。
2. var a = function(){alert(1);} a();//定义一个变量为函数,然后调用执行这两种调用方式其实是一样的。所以Dialog = (function(){
return{a:'1',b:'2'}//返回一个object
})();
其实相当于Dialog = {a:'1',b:'2'}
也可以改得通俗易懂一点
var a = function(){return {a:'1',b:'2'}}
Dialog = a();
alert(Dialog.a)//will alert 1
受教啦。(function(){body})()原来这样子可以建一个匿名函数,除了在那个interfaceInit之前声明相关变量没有其它方法可以调用Dialog了吗?!
Dialog.add(123);
function interfaceInit(){
Dialog = (function(){
var now = null;
return {
add: function(id){
alert(id);
},
getNow: function(){
alert(now);
}
}
})();
}
interfaceInit();
Dialog.add(123);
</script>
就这么简单
<JavaScript权威指南(第五版)>(也就是O'reilly的犀牛书),重点学习一下与函数,对象相关的章节
然后,可以找一个比较流行的js框架学习一下他的源代码,比如prototype