方法一
利用闭包的特性
var myObject = (function(){
var __name = 'sven'; // 私有(private)变量
return {
getName: function(){ // 公开(public)方法
return __name;
}
}
})();
console.log( myObject.getName() ); // 输出:sven
console.log( myObject.__name ) // 输出:undefined
方法二
利用symbol是唯一的特性
var MyClass = (function() {
// module scoped symbol
var key = Symbol("key");
function MyClass(privateData) {
this[key] = privateData;
}
MyClass.prototype = {
getKey: function() {
return this[key]
}
};
return MyClass;
})();
var c = new MyClass("hello")
c['key'] // undefined
c.getKey() // hello
留言