|
155 | 155 |
|
156 | 156 |
|
157 | 157 | //【动态原型模式】 |
158 | | -// function Person(name, age) { |
159 | | -// this.name = name; |
160 | | -// this.age = age; |
161 | | - |
162 | | -// if (typeof this.sayName == 'function') return; |
163 | | -// // console.log('create'); |
164 | | -// Person.prototype.sayName = function() { |
165 | | -// console.log(this.name); |
166 | | -// } |
167 | | - |
168 | | -// Person.prototype.sayAge = function() { |
169 | | -// console.log(this.age); |
170 | | -// } |
171 | | -// } |
| 158 | +function Person(name, age) { |
| 159 | + this.name = name; |
| 160 | + this.age = age; |
| 161 | + |
| 162 | + if (typeof this.sayName == 'function') return; |
| 163 | + // console.log('create'); |
| 164 | + Person.prototype.sayName = function() { |
| 165 | + console.log(this.name); |
| 166 | + } |
| 167 | + |
| 168 | + Person.prototype.sayAge = function() { |
| 169 | + console.log(this.age); |
| 170 | + } |
| 171 | +} |
172 | 172 |
|
173 | | -// var person1 = new Person('xyx', 123), |
174 | | -// person2 = new Person('yyy', 456); |
| 173 | +var person1 = new Person('xyx', 123), |
| 174 | + person2 = new Person('yyy', 456); |
175 | 175 |
|
176 | | -// console.log(person1); |
177 | | -// console.log(person2); |
| 176 | +console.log(person1); |
| 177 | +console.log(person2); |
178 | 178 |
|
179 | | -// person1.sayName(); |
180 | | -// person2.sayAge(); |
| 179 | +person1.sayName(); |
| 180 | +person2.sayAge(); |
181 | 181 |
|
182 | 182 | //动态原型模式问题 |
183 | 183 | //动态原型模式实际是是对组合模式进行了一次包装,将对原型对象的初始化操作放入构造函数内部了。 |
|
228 | 228 |
|
229 | 229 |
|
230 | 230 | //【稳妥构造函数模式】 |
231 | | -function Person(name, age) { |
232 | | - var o = new Object(); |
| 231 | +// function Person(name, age) { |
| 232 | +// var o = new Object(); |
233 | 233 |
|
234 | | - //可以定义些私有变量 |
| 234 | +// //可以定义些私有变量 |
235 | 235 |
|
236 | | - o.sayName = function() { |
237 | | - console.log(name); |
238 | | - }; |
| 236 | +// o.sayName = function() { |
| 237 | +// console.log(name); |
| 238 | +// }; |
239 | 239 |
|
240 | | - return o; |
241 | | -} |
| 240 | +// return o; |
| 241 | +// } |
242 | 242 |
|
243 | | -var friend = Person('Nicholas', 29); |
244 | | -friend.sayName(); |
| 243 | +// var friend = Person('Nicholas', 29); |
| 244 | +// friend.sayName(); |
245 | 245 |
|
246 | 246 | //稳妥构造函数问题 |
247 | 247 | //稳妥对象是指没有公共属性,而且其方法也不引用 this 的对象。 |
|
0 commit comments