|
155 | 155 | //【原型式继承】 |
156 | 156 |
|
157 | 157 | //【寄生式继承】 |
158 | | -function createAnother(original) { |
159 | | - var clone = Object.create(original); |
160 | | - clone.sayHi = function() { |
161 | | - console.log('hi'); |
162 | | - }; |
163 | | - return clone; |
164 | | -} |
| 158 | +// function createAnother(original) { |
| 159 | +// var clone = Object.create(original); |
| 160 | +// clone.sayHi = function() { |
| 161 | +// console.log('hi'); |
| 162 | +// }; |
| 163 | +// return clone; |
| 164 | +// } |
165 | 165 |
|
166 | | -var person = { |
167 | | - name: 'abc', |
168 | | - firends: ['Shelby', 'Court', 'Van'] |
169 | | -}; |
| 166 | +// var person = { |
| 167 | +// name: 'abc', |
| 168 | +// firends: ['Shelby', 'Court', 'Van'] |
| 169 | +// }; |
170 | 170 |
|
171 | | -var anotherPerson = createAnother(person); |
172 | | -anotherPerson.sayHi(); |
| 171 | +// var anotherPerson = createAnother(person); |
| 172 | +// anotherPerson.sayHi(); |
173 | 173 |
|
174 | 174 | //寄生式继承问题 |
175 | 175 | //在主要考虑对象而不是自定义类型和构造函数的情况下,寄生式继承也是一种有用的模式。 |
| 176 | +//使用寄生式继承来为对象添加函数,会由于不能做到函数复用而降低效率;这一点与借用构造函数类似。 |
176 | 177 |
|
177 | 178 | //【寄生式继承】 |
178 | 179 |
|
179 | | -//寄生组合式继承 |
| 180 | +//【寄生组合式继承】 |
| 181 | +function inheritPrototype(subType, superType) { |
| 182 | + var prototype = Object.create(superType.prototype); |
| 183 | + prototype.constructor = subType; |
| 184 | + subType.prototype = prototype; |
| 185 | +} |
| 186 | + |
| 187 | +function SuperType(name) { |
| 188 | + this.name = name; |
| 189 | + this.colors = ['red', 'blue', 'green']; |
| 190 | +} |
| 191 | + |
| 192 | +SuperType.prototype.sayName = function() { |
| 193 | + console.log(this.name); |
| 194 | +}; |
| 195 | + |
| 196 | +function SubType(name, age) { |
| 197 | + SubType.call(this, name); |
| 198 | + this.age = age; |
| 199 | +} |
| 200 | + |
| 201 | +inheritPrototype(SubType, SuperType); |
| 202 | + |
| 203 | +SubType.prototype.sayAge = function() { |
| 204 | + console.log(this.age); |
| 205 | +}; |
| 206 | +//【寄生组合式继承】 |
180 | 207 |
|
181 | 208 | </script> |
182 | 209 | </body> |
|
0 commit comments