private static member in javascript

原文链接
[url]http://www.litotes.demon.co.uk/js_info/private_static.html[/url]
期待简译。

有一些代码,整得有些过了,但还是很值得参考。在jct的代码中看到了类似的用法。
在js中隐藏变量还是有必要的,否则和其他的js库冲突,就会很麻烦,很难找到bug。

贴几段代码,明白人都看得懂。
var MyObject = (function(){
/*private static (class) member*/
var counter = 0;
/*private static method.*/
function incrementCounter(){
return counter++;
};
/*class constructor.*/
function constructorFn(id){
this.id = id;
var self = this;
/*call private static (class)
method and assign the returned
index to a private instance member.*/
var index = incrementCounter();
/*privileged instance method.*/
this.getIndex = function(){
return index;
};
};
/*privileged static (class) method
(a property of the constructor)*/
constructorFn.getNoOfInsts = function(){
return counter;
};
/*public instance method privaliged at the
class level*/
constructorFn.prototype.pubInstMethod = function(){
...
};
/*return the constructor.*/
return constructorFn;
})(); //simultaneously define and call (one-off)!

/*public static member*/
MyObject.pubStatic = "anything"

/*public instance member*/
MyObject.prototype.pubInstVar = 8;


再来一段
var global = this;
(function(){
var classGroupMember = 3;
function privateToClassGroup(){
/*this method could be a utilitiy
for the classes in the group or used
as an internal object constructor.*/
...
};
global.MyObject1 = function(){
var privteStaticMember = 4;
function privateStaticMethod(){
...
};
function constructorFn(id){
...
};
/*return the constructor.*/
return constructorFn;
}(); //simultaneously define and call!
global.MyObject2 = function(){
function constructorFn(id){
...
};
/*return the constructor.*/
return constructorFn;
}(); //simultaneously define and call!
global.MyObject3 = function(){
function constructorFn(id){
...
};
/*return the constructor.*/
return constructorFn;
}(); //simultaneously define and call!
})(); //simultaneously define and call!


再来一段:
/*constructor function */
function MyObject(){
...
}

MyObject.prototype = (function(){
/*private static (class) member*/
var privateStaticProp = "anything";
/*private static method .*/
function privateStatic Method = function(){
...
}
return ({
/*These functions objects are shared by
all instances that uses this prototype
and they have access to the private static
members within the closure that returns
this object*/
publicInstanceMethod:function(){
...
},
setSomething:function(s){
privateStaticProp = s;
}
});
})();

/*public instance member*/
MyObject.prototype.pubInstVar = 8;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值