<分区>
我现在正在测试一个简单的 Javascript“类”。我注意到我的私有(private)函数中的“this”并不指向对象本身,而是指向全局范围(窗口)。
为什么?
信息:我想保持模式私有(private),所以我使用 var 模式而不是 this.mode。 我还想将两个内部函数都保密,这样用户就无法访问它。 我基本上使用 .prototype 将公共(public)函数添加到 myStorage 以访问私有(private)成员。
我的代码:
var myStorage = function(mymode) {
var mode = mymode;
function privateFunctionA() {
// access this.mode to read mymode from constructor but
// this is pointing to window
};
function privateFunctionB() {
// access this.mode to read mymode from constructor but
// this is pointing to window
};
// check for indexeddb, websql and localstorage
if(mymode == 'A') {
privateFunctionA();
} else {
privateFunctionB();
}
};
myStorage.prototype.publicFunc = function() {
console.log(this.mode); // does this work?
}
var data = new myStorage();