JavaScript面向对象设计

今天在学习JavaScript的面向对象设计,看的是第2版的《JavaScript高级程序设计》,将那些模式都记录下。

  1  ////创建对象
2 var person = new Object();
3 person.name = "Fan"
4 person.age = 23;
5 person.job = "Coder";
6
7 person.sayName = function(){
8 alert("My name is "+this.name);
9 };
10
11 person.sayName();
12
13 //工厂模式
14 function createPerson(name,age,job){
15 var o = new Object();
16 o.name = name;
17 o.age = age;
18 o.job = job;
19 o.sayName = function(){
20 alert("My name is "+this.name);
21 };
22 return o;
23 }
24 var person = createPerson("Lintao",22,"Coder");
25 person.sayName();
26
27 //构造函数模式
28 function Person(name,age,job){
29 this.name = name;
30 this.age = age;
31 this.job = job;
32 this.sayName = function(){
33 alert("my name is "+this.name);
34 };
35 }
36 var person1 = new Person("mutou",21,"coder");
37 person1.sayName();
38
39
40 //原型模式
41 function Person1(){
42 }
43 Person1.prototype.name = "lbj";
44 Person1.prototype.age = 21;
45 Person1.prototype.job = "coder";
46 Person1.prototype.sayName = function(){
47 alert("my name is "+this.name);
48 };
49
50 var person2 = new Person1();
51 person2.sayName(); //lbj
52 var person3 = new Person1();
53 person3.sayName(); //还是lbj
54
55
56 //组合使用构造函数模式和原型模式
57 function Person2(name,age,job){
58 this.name = name;
59 this.age = age;
60 this.job = job;
61 this.friends = ["Shelby","Court"];
62 }
63 Person2.prototype = {
64 constructor : Person2,
65 sayName : function(){
66 alert("my name is "+this.name);
67 }
68 }
69
70 var person4 = new Person2("FanFan",22,"Coder");
71 var person5 = new Person2("MUMU",22,"Doctor");
72 person4.friends.push("Van");
73 alert(person4.friends); //Shelby,Court,Van
74 alert(person5.friends); //Shelby,Court
75
76 //动态原型模式
77 function Person3(name,age,job){
78 //属性
79 this.name = name;
80 this.age = age;
81 this.job = job;
82 //方法
83 if (typeof this.sayName != "function"){
84 Person3.prototype.sayName = function(){
85 alert("my name is "+this.name);
86 };
87 }
88 }
89 var person6 = new Person3("HAHA",34,"Software Engineer");
90 person6.sayName();
91
92 //寄生构造函数模式
93 function Person4(name,age,job){
94 var o = new Object();
95 o.name = name;
96 o.age = age;
97 o.job = job;
98 o.sayName = function(){
99 alert("my name is "+ this.name);
100 };
101 return o;
102 }
103 var person7 = new Person("LALA",19,"teacher");
104 person7.sayName();
105
106 //稳妥构造函数模式
107 function Person5(name,age,job){
108 //创建要返回的对象
109 var o = new Object();
110 //可以在这里定义私有变量和函数
111 //添加方法
112 o.sayName = function(){
113 alert("my name is "+ name);
114 };
115 return o;
116 }
117 var person8 = Person5("AAA",44,"Teacher");
118 person8.sayName();
posted @ 2012-04-06 20:04  木头lbj  阅读(217)  评论(0编辑  收藏  举报