首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

利用闭包兑现私有成员的单体(Singleton),访问内部成员时出现的差别,不知道为何

2012-08-09 
利用闭包实现私有成员的单体(Singleton),访问内部成员时出现的差别,不知道为何代码如下:JScript codevar L

利用闭包实现私有成员的单体(Singleton),访问内部成员时出现的差别,不知道为何
代码如下:

JScript code
         var LIB = function () {             var _request1 = function () {                 this._name = "alert request1 name!";                 this._id = "alert request1 id!";             };             var _request2 = new function () {                 this._name = "alert request2 name!";                 this._id = "alert request2 id!";             };             return {                 request1: _request1,                 request2: _request2             };         } ();         function jst() {             var tt1 = new LIB.request1();//正常             //var tt2 =LIB.request2();//这里会报错              alert(tt1._name);//正常             //alert(tt2._name);//访问不了         }

HTML code
<input type="button" id="btn_test" style="width:120px;height:30px" value="测试" onclick="jst()" />

在LIB内,直接new function(),然后其暴露出来能被访问到,可是为何不行呢?如上代码,直接访问request2会报错,reqeust1正常!

[解决办法]
request2已经是一个object了

alert(LIB.request2._name);

如果可以的话 你在带控制台的浏览器中
console.log(LIB)
就明白了

热点排行
Bad Request.