原文链接
http://www.litotes./js_info/private_static.html 期待简译。 有一些代码,整得有些过了,但还是很值得参考。在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! 再来一段:
|
|