我正在使用以下显示原型模式:
var myClass = function () {
var that = this;
// private member : An instance of another class which requires some private
// members of myClass to be passed as callbacks in its parameters
this.externalClassInstance = new externalClass({
callbackName: function () {
myClass.prototype.myFunction.call(that);
}
});
};
myClass.prototype = function () {
// myFunction remains a private member until I define it in the return statement to make it public
var myFunction = function () {
alert("hello");
};
return {
// Uncommenting the next line would make the code work but would also make myFunction public
// myFunction : myFunction
};
}();
var externalClass = function (data) {
data.callbackName();
};
var myClassInstance = new myClass();
上面的代码不起作用,因为我没有将myFunction
公开。
这是因为仅用作回调的myFunction
总是在myClass
的范围内运行,我不希望任何拥有myClass对象的人调用构造函数。
如何在不公开myFunction
的情况下使此代码正常工作?
我理解的一种方法是将myFunction作为类的私有变量(通过在构造函数中定义)而不是原型。还有其他更好的解决方案吗?
答案 0 :(得分:0)
我不会使用该模式,而是使用模块模式来封装您的私有函数:
(function(ns) {
function myFunction()
{
alert('hello');
}
ns.myClass = function()
{
var that = this;
this.externalClassInstance = new externalClass({
callbackName: function () {
myFunction.call(that);
}
});
}
}(window));