[英]Singleton Access Private methods acces public methods
我已经创建了一个类,但是在访问私有方法中的公共方法时遇到了一些麻烦。 我的例子是这样的:
var mySingleton = (function () {
function init() {
function privateMethod(){
publicMethod();
//this.publicMethod() also doesn't work
}
privateMethod();
return {
publicMethod: function () {
console.log( "The private method called me!" );
}
};
};
return {
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
var singleton = mySingleton.getInstance();
范围似乎完全不同。 我应该以其他方式创建单例吗?
那么为什么不想使用这样的东西:
var mySingleton = (function () {
/*private methods*/
return {
/*public methods*/
}
})();
如果您的问题正式提出,您需要像这样更改代码
...
function init() {
function privateMethod(){
publicMethod();//OK
}
privateMethod();
function publicMethod(){
console.log( "The private method called me!" );
}
return {
publicMethod: publicMethod
};
};
...
不要使用该附加的init
函数。 并且您将必须访问instance
上的公共方法,即您从init
返回的对象。
var mySingleton = (function () {
var instance = null;
function privateMethod(){
instance.publicMethod();
}
return {
getInstance: function () {
if ( !instance ) {
instance = {
publicMethod: function () {
console.log( "The private method called me!" );
}
};
privateMethod();
}
return instance;
}
};
})();
var singleton = mySingleton.getInstance();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.