之前介绍了,js面向对象编程的相关内容。本人在实际项目中,也用到js面向对象的编程,不说废话直接上代码。
定义两个实例 AccountItem (用户) AccountList (用列表) :
//名前空間
var EIMS = EIMS || {};
EIMS.AccountItem = (function(){
//constructor
function AccountItem(id, shisha_id, busho_id, name, del_flag){
this.id = id;
this.shisha_id = shisha_id;
this.busho_id = busho_id;
this.name = name;
this.del_flag = del_flag;
}
//accesser
AccountItem.prototype.getId = function(){
return this.id;
};
AccountItem.prototype.getShishaId = function(){
return this.shisha_id;
}
AccountItem.prototype.getBushoId = function(){
return this.busho_id;
}
AccountItem.prototype.getName = function(){
return this.name;
}
AccountItem.prototype.getDelFlag = function(){
return this.del_flag;
}
return AccountItem;
})();
EIMS.AccountList = (function(){
//constructor
function AccountList(shisha_id, busho_id, del_flag, or_id){
this.search_shisha_id = shisha_id;
this.search_busho_id = busho_id;
this.search_del_flag = del_flag;
this.search_or_id = or_id;
}
AccountList.prototype.getArray = function(url){
var arr = new Array();
var params = $H({shisha_id : this.search_shisha_id, busho_id : this.search_busho_id, del_flag : this.search_del_flag, or_id : this.search_or_id});
var callback_success = function(objXml){
var id, shisha_id, busho_id, del_flag, name;
var itemTags = objXml.getElementsByTagName("item");
for(var i = 0; i < itemTags.length; i ++){
id = "";
shisha_id = "";
busho_id = "";
del_flag = 0;
name = "";
tmp = itemTags[i].firstChild;
while(tmp != null){
if(tmp.nodeName.toLowerCase() == "id"){
if(tmp.firstChild != null) id = tmp.firstChild.nodeValue;
}else if(tmp.nodeName.toLowerCase() == "shisha_id"){
if(tmp.firstChild != null) shisha_id = tmp.firstChild.nodeValue;
}else if(tmp.nodeName.toLowerCase() == "busho_id"){
if(tmp.firstChild != null) busho_id = tmp.firstChild.nodeValue;
}else if(tmp.nodeName.toLowerCase() == "del_flag"){
if(tmp.firstChild != null) del_flag = tmp.firstChild.nodeValue;
}else if(tmp.nodeName.toLowerCase() == "name"){
if(tmp.firstChild != null) name = tmp.firstChild.nodeValue;
}
tmp = tmp.nextSibling;
}
arr.push(new EIMS.AccountItem(id, shisha_id, busho_id, name, del_flag));
}
};
new Ajax.Request(
url,
{
method : 'get',
asynchronous : false,
parameters : params,
onSuccess : function(req){
callback_success(req.responseXML);
},
onFailure : function(req){
alert(req.responseText.trim());
},
onException : function(req, e){
alert(e.message);
}
}
);
return arr;
};
return AccountList;
})();
使用实例:
//生成AccountList实例 使用构造函数属性初始化
var obj = new EIMS.AccountList($("search_shisha_id").value, $("search_busho_id").value, 0, "");
//调用getArray方法,返回 数组对象
var arr = obj.getArray(account_list_url);
//生成AccountItem实例,利用构造函数设置属性值,并将实例插入到数组对象中
arr.unshift(new EIMS.AccountItem("", "", "", "担当", 1));
以上是项目中实际使用的一段代码,粗浅非常,请多包涵。