【发布时间】:2014-10-07 20:43:29
【问题描述】:
我见过有人尝试在 JS 中实现私有方法。但是他们都有不同的问题,比如这个:JavaScript private methods
我相信我的尝试也存在一些问题。但是除了在严格模式下不允许开销和调用者之外,我的实现有什么问题? 您可以在 jsfiddle 中看到一个工作示例:http://jsfiddle.net/rabbit_aaron/oqpen8c8/17/
实现也贴在这里:
var CLASS = function () {
this.publicFunctions = {};
this.PROTOTYPE = {};
var _class = function () {
this.constructor.apply(this, arguments);
};
_class.prototype = this.PROTOTYPE;
_class.prototype.validateAccess = CLASS.prototype.validateAccess;
_class.prototype.constructor = function () {};
_class.prototype.publicFunctions = this.publicFunctions;
this.finalClass = _class;
return this;
};
CLASS.prototype.validateAccess = function (caller) {
if (this.publicFunctions[caller] !== caller) {
throw 'Accessing private functions from outside of the scope';
}
return true;
};
CLASS.prototype.setConstructor = function (func) {
this.PROTOTYPE.constructor = func;
};
CLASS.prototype.addPrivateFunction = function (name, func) {
this.PROTOTYPE[name] = function () {
this.validateAccess(this[name].caller);
func.apply(this, arguments);
};
return this;
};
CLASS.prototype.addPublicFunction = function (name, func) {
this.PROTOTYPE[name] = func;
this.publicFunctions[this.PROTOTYPE[name]] = this.PROTOTYPE[name];
return this;
};
CLASS.prototype.getClass = function () {
return this.finalClass;
};
【问题讨论】:
-
有些人只是在范围内创建一个变量并为其分配一个函数。非常私密。
-
似乎很难维护。为什么不使用简单的模块模式?
-
它只是给你的代码增加了一些复杂性,但对你的私有函数没有保护。因此,与例如相比,我没有看到任何真正的优势。以
_为函数添加前缀,并在文档中使用jsdoc将其标记为私有。 -
如何从子类继承?在您的示例中,我可以看到继承自 CLASS 的
Person类。如果我想创建一个继承自Person的Lady和Gentleman类怎么办? -
这个问题不应该发到codereview.stackexchange.com吗?
标签: javascript function oop private