js---26組合模式
阿新 • • 發佈:2017-05-21
pan col utf-8 led head ons javascrip public 方法
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type=text/javascript charset=utf-8src=../commons/CommonUtil.js ></script> <script> // 組合模式 /* * 場景模擬: * -> 公司 * -> 財務部門 * -> 張一 * -> 張二 * -> 張三 * -> 銷售部門 * -> 張四 * -> 張五 * -> 張六 * * 實際的任務具體是落實到人上去實施的 也就是說只有人才具有具體的方法實現 **/ var Org = function(name){ this.name = name ; this.depts = [] ; }; Org.prototype = { constructor:Org , addDepts:function(child){//形參不寫數據類型 this.depts.push(child);//this一般指的是Org對象 return this ; } , getDepts:function(){ return this.depts; } }; var Dept = function(name){ this.name = name ; this.persons = [] ; }; Dept.prototype = { constructor:Dept , addPersons: function(child){ this.persons.push(child); return this ; } , getPersons:function(){ return this.persons; } }; var Person = function(name){ this.name = name ; }; Person.prototype = { constructor : Person , hardworking : function(){ document.write(this.name + ‘...努力工作!‘); } , sleeping : function(){ document.write(this.name + ‘...努力睡覺!‘); } }; var p1 = new Person(‘張1‘); var p2 = new Person(‘張2‘); var p3 = new Person(‘張3‘); var p4 = new Person(‘張4‘); var p5 = new Person(‘張5‘); var p6 = new Person(‘張6‘); var dept1 = new Dept(‘開發部門‘); dept1.addPersons(p1).addPersons(p2).addPersons(p3); var dept2 = new Dept(‘銷售部門‘); dept2.addPersons(p4).addPersons(p5).addPersons(p6); var org = new Org(‘bjsxt‘); org.addDepts(dept1).addDepts(dept2); // 需求: 具體的讓一個人(張3)去努力工作 //org.getDepts() org.hardworking(‘開發部門‘); for(var i = 0 ,depts = org.getDepts(); i<depts.length;i++ ){//for循環中也不寫數據類型 for(var j = 0 ,persons = depts[i].getPersons(); j < persons.length ; j++){ if(persons[j].name === ‘張6‘){ persons[j].hardworking(); } } } </script> </head> <body> </body> </html>
js---26組合模式