1. 创建工厂类
// 对象的工厂类 var ObjFactory=new Object(); ObjFactory.createObj=function (){ //创建产品的方法 var obj = new Object();//要生产的产品 obj.name = "hero";//产品的属性 obj.showName=showName;//产品所具备的功能 obj.getElement=getElement;//产品所具备的功能 obj.getTextFromXMLByPath=getTextFromXMLByPath;//产品所具备的功能 return obj;//返回产品的实例信息 }
2. 实现产品具备的功能
//弹出属性信息 function showName(){alert(this.name);} //根据id获取指定表单的值 function getElement(A,B){ var t=document.getElementById(A); var value=t.value+B; return value; } //输入xml和路径,获取指定路径下xml节点的值 function getTextFromXMLByPath(xmlStr,path){ var responseDoc = new ActiveXObject("MSXML.DOMDocument"); responseDoc.loadXML(xmlStr); var value = responseDoc.selectSingleNode(path).text; return value; } //$ 的神秘--js支持$作为方法名,对象也是可以的。 $=function(A,B){ var t=document.getElementById(A); var value=t.value+B; return value; }
3. 编写测试类
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<input type="button" id="1" value="test" onclick="$(1)"/>
<script>
document.write(ObjFactory.createObj().name);
ObjFactory.createObj().showName();
document.write(ObjFactory.createObj().getElement(1,'大家好'));
var xmlStr="<request>rteVerRan</request>";
xmlStr="1";
document.write(ObjFactory.createObj().getTextFromXMLByPath(xmlStr,"/request"));
</script>
</body>
</html>
4. 测试结果
hero
弹出alert("VerRan");
test大家好