JavaScript专家
辅助功能的推荐方法是什么?我想选择一种技术,然后用它来创建我的新“类”。
以下是我考虑过的设计方案:
选项1:外部作用域中的助手函数,使用实例的上下文调用
function createPane (pane) {
// logic to create pane
var proto = Object.create(this.paneList);
$.extend(paneProto, pane);
return paneProto;
}
Panes.prototype.initialize = function (panes) {
var _this = this;
_.each(panes, function () {
_this.panes.push(createPane.call(_this, this));
});
}
createPane
未在实例上发布。createPane
可在其他范围内访问。选项2:关闭时的辅助函数,使用实例的上下文调用
Panes.prototype.initialize = (function () {
function createPane (pane) {
// same logic as last createPane
}
return function (panes) {
// same logic as before - calls createPane
}
})();
createPane
未在实例上发布。选项3:将_添加到名称以指示私有方法
Panes.prototype._createPane = function (pane) {
// same logic as last createPane
}
Panes.prototype.initialize = function (panes) {
// same logic as last, except calls this._createPane
}
_createPane
的隐式上下文就是实例。来自外部的可测试性。