我的代码类似于:
(function (global) {
var MyObject = function (arg1, arg2) {
this.publicVar = arg1;
this._internalVar = arg2;
};
MyObject.prototype = {
publicFunc: function (param) {
return param + this._internalVar;
}
};
global.MyObject = MyObject;
}(window));
我可以以某种方式让UgilfyJS破坏_internalVar
因为它不打算在这个范围之外使用吗?我知道它可以通过使用高级压缩等的闭包编译器完成,但我使用anvil来构建和uglifyjs来缩小。
答案 0 :(得分:2)
为了保护_internalVar,我试过
(function (global) {
var MyObject = function () {};
MyObject.prototype = (function(){
var _internalVar = 2;
return {
publicVar: 1,
publicFunc: function (param) {
return param +' '+ _internalVar;
}
};
})();
global.MyObject = MyObject;
}(window));
并尝试访问
console.log( ( new window.MyObject()).publicVar );
打印 1
console.log( ( new window.MyObject())._internalVar );
是undefined
console.log( ( new window.MyObject()).publicFunc('value') );
打印值2
有关详细信息,请查看http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript