可以在JS库代码结构中混合JavaScript对象文本和原型吗?
我正在构建一个JavaScript库,它目前使用对象文本,现在我正在重建它,以使用原型 下面是我当前应用程序的一部分,你可以看到它将几个模板解析函数组织在一个可以在JS库代码结构中混合JavaScript对象文本和原型吗?,javascript,Javascript,我正在构建一个JavaScript库,它目前使用对象文本,现在我正在重建它,以使用原型 下面是我当前应用程序的一部分,你可以看到它将几个模板解析函数组织在一个templates对象下 对象文字格式,以保持相关函数的组织 下面是我的新原型设计的格式。。。 原型格式 问题: 使用我的新原型格式,是否可以像上面的模板一样组织相关功能?将对象中的相关项分组 听起来好像您正试图使名称空间类似于PHP。您可以实现类似的功能,如: var Templates = { Sidebar: Sideba
templates
对象下
对象文字格式,以保持相关函数的组织
下面是我的新原型设计的格式。。。 原型格式
问题: 使用我的新原型格式,是否可以像上面的模板一样组织相关功能?将对象中的相关项分组 听起来好像您正试图使
名称空间
类似于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中,并使其可注入,而无需破坏全局命名空间
最初的方法没有什么问题,只是使用了匿名函数,所以不能给它们原型方法(因为不能引用它们).您可以像在旧代码中一样将原型本身初始化为对象。@Pointy我不确定我是否完全遵循了如何实现,您可以发布一个示例吗?
Sidebar.prototype={foo:function(x,y){…},bar:function(){…}代码>@Pointy啊是的,在我忘记之前我已经看过了,谢谢!我太习惯于看到原型示例有一个函数值,我想我当时认为不是possibble@Pointy如果你想把它作为一个答案,我觉得它最能回答我的问题
/**
* 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);
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);