因为js里没有访问控制符,所以着实让我头晕了一阵。现在基本搞清楚了,这里留个笔记。首先要先看明白什么是js的闭包:JavaScript闭包。或者有时间的话,可以好好看看Pro JavaScript Design Patterns。这篇文章里只会写怎么做而不是为什么这么做,不作深究。
公有:
[codesyntax lang="javascript"]
var CLS = function() { this.see = 'see!'; // public param this.getSee = function() { return this.see; }; this.setSee = function(val) { this.see = val; return true; }; }; var cls = new CLS(); console.log(cls.see); // see! console.log(cls.setSee('see?')); // true console.log(cls.getSee()); // see? cls.see = 'changed'; console.log(cls.getSee()); // changed console.log(CLS.see); // undefined
[/codesyntax]
私有:
[codesyntax lang="javascript"]
var CLS = function() { var _see = 'see!'; // private param this.getSee = function() { return _see; // cannot use this._see }; this.setSee = function(val) { _see = val; // cannot use this._see return true; }; }; var cls = new CLS(); console.log(cls._see); // undefined console.log(cls.setSee('see?')); // true console.log(cls.getSee()); // see? console.log(typeof cls._see); // undefined cls._see = 'changed'; // created a new _see in public scope console.log(typeof cls._see); // string console.log(cls.getSee()); // see? console.log(CLS._see); // undefined
[/codesyntax]
静态:
[codesyntax lang="javascript"]
var CLS = function() {}; CLS.SEE = 'see!'; // static param CLS.HELLO_WORLD = function() { return 'HELLO WORLD!'; }; console.log(CLS.SEE); // see! console.log(CLS.HELLO_WORLD()); // HELLO WORLD!
[/codesyntax]