1.不带prototype的封装例
example1.js
if (typeof Tgd === ‘undefined’) {
var Tgd = function() {};
}
if (typeof Tgd.widgets === ‘undefined’) {
Tgd.Widgets = function() {};
}
Tgd.Widgets.Dialog = {};
// 常量
Tgd.Widgets.Dialog.ELEMENT_DIALOG_CLASS = “tgd-rc-all”;
// 变量
Tgd.Widgets.Dialog.elementDialog = null;
Tgd.Widgets.Dialog.createDialog = function(id, settings) {
var self = this;
this.elementDialog = document.getElementById(id);
this.elementDialog.setAttribute(“class”, this.ELEMENT_DIALOG_CLASS);
this.elementDialogHeader.addEventListener(“mousemove”, function(e) {self.moveMouseDialogHeader(e);}, false);
}
Tgd.Widgets.Dialog.moveMouseDialogHeader = function(event){
this.elementDialog.style.top = "0px’;
}
// jsp 调用
var dialog = Tgd.Widgets.Dialog;
dialog.createDialog(“end-dialog”,{height:420, width:480,initContent:’’});
2.带prototype的封装例
example2.js
if (typeof Tgd = ‘undefined’) {
var Tgd = function(){
};
}
if (typeof Tgd.Widgets = ‘undefined’) {
Tgd.Widgets = function() {
};
}
Tgd.Widgets.LinearGauge = function(doc) {
if (doc) {
this.objDoc = doc;
} else {
this.objDoc = document;
}
this.Id = null;
this.elParentDiv = null;
Tgd.Widgets.LinearGauge.prototype.load = function(parentDivId,id,displayMinValue,displayMaxValue,minValue,maxValue,textString) {
this.elParentDiv = document.getElementById(parentDivId);
}
Tgd.Widgets.LinearGuage.prototype.setValue = function(value) {
}
}
// jsp 调用
var linearGauge = new Tgd.Widgets.LinearGauge();
linearGauge.load(‘aaa’,‘bbb’,-0.26,2.56,1,1.70,‘1V’);
linearGauge.setValue(1.5);
3.namespace和方法的标准定义
XXX.js
// namespace的定义
var Tgd= Tgd || {};
Tgd.Widgets=Tgd.Widgets || {};
// class 定义
Tgd.Widgets.Dialog = Tgd.Widgets.Dialog || {};
// 类的定数定义
Tgd.Widgets.Dialog.ELEMENT_DIALOG_STYLE_Z_INDEX=18001;
Tgd.Widgets.Dialog.CREATE_TYPE = Object.freeze({
OK:1,
CANSEL:2;
ABORT:3
});
// 类的变数定义
Tgd.Widgets.Dialog.elementDialog = null;
// 类的方法定义
Tgd.Widgets.Dialog.createDialog = function(id, settings){
var self = this;
this.CREATE_TYPE.OK;
}
4.将Html转成HTMLDocument对象
objHTMLDocument = new DOMParser().parseFormString(htmlContent, “text/html”);
groupWork = objHTMLDocument .getElementById(“groupId”);