我正在构建一个 JavaScript 库,当前使用对象文字,现在我正在重建它以使用原型(prototype)。
下面是我当前应用程序的一部分,您可以看到它在 templates
对象下组织了多个模板解析函数...
对象文字格式以保持相关函数的组织
templates: {
parse: function(template, data){
},
sidebarTemplate: function() {
},
sidebarPanelTemplate: function(panelOptionsObj) {
},
sidebarPanelBackButtonTemplate: function(panelOptionsObj) {
},
sidebarPanelLoaderTemplate: function(panelOptionsObj) {
},
},
<小时/>
现在下面是我的新原型(prototype)设计的格式...
原型(prototype)格式
/**
* Example Prototype Library Structure
*
* @param {[type]} $ [description]
* @param {[type]} window [description]
* @param {[type]} document [description]
* @param {[type]} undefined [description]
* @return {[type]} [description]
*/
(function($, window, document, undefined) {
'use strict';
var defaults = {
fullScreen: true
};
var SideBar = function(element) {
// You can access all CoreJS variables and functions like this.
this.core = $(element).data('corejs');
this.$el = $(element);
this.core.s = $.extend({}, defaults, this.core.s)
this.init();
return this;
}
SideBar.prototype.init = function() {
};
/**
* Destroy function must be defined.
* CoreJS will automatically call your module destroy function
* before destroying the gallery
*/
SideBar.prototype.destroy = function() {
}
})(jQuery, window, document);
<小时/>
问题
使用我的新原型(prototype)格式,是否可以组织相关功能,例如上面的模板功能?
最佳答案
将对象中的相关项分组
听起来您正在尝试像 PHP 中那样创建命名空间
。您可以实现类似的东西:
var Templates = {
Sidebar: Sidebar,
Header: Header
};
function Sidebar(width) {
this.width = width;
}
Sidebar.prototype.setWidth = setWidth;
function setWidth(width) {
this.width = width;
}
function Header(height) {
this.height = height;
}
var x = new Templates.Sidebar(3);
x.setWidth(5)
console.log(x);
只需很少的努力,您就可以将组件包装在 IIFE 中并使其可注入(inject),而不会破坏全局命名空间。
您原来的方法没有任何问题,只是您使用了匿名函数,因此您无法为它们提供原型(prototype)方法(因为您无法引用它们)。
关于javascript - 您可以在 JS 库代码结构中混合 JavaScript 对象文字和原型(prototype)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41556105/