X Tutup
Skip to content

Commit 87e0d9d

Browse files
committed
update
1 parent 46741f9 commit 87e0d9d

File tree

1 file changed

+41
-14
lines changed

1 file changed

+41
-14
lines changed

OO/inherit.html

Lines changed: 41 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -155,28 +155,55 @@
155155
//【原型式继承】
156156

157157
//【寄生式继承】
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+
// }
165165

166-
var person = {
167-
name: 'abc',
168-
firends: ['Shelby', 'Court', 'Van']
169-
};
166+
// var person = {
167+
// name: 'abc',
168+
// firends: ['Shelby', 'Court', 'Van']
169+
// };
170170

171-
var anotherPerson = createAnother(person);
172-
anotherPerson.sayHi();
171+
// var anotherPerson = createAnother(person);
172+
// anotherPerson.sayHi();
173173

174174
//寄生式继承问题
175175
//在主要考虑对象而不是自定义类型和构造函数的情况下,寄生式继承也是一种有用的模式。
176+
//使用寄生式继承来为对象添加函数,会由于不能做到函数复用而降低效率;这一点与借用构造函数类似。
176177

177178
//【寄生式继承】
178179

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+
//【寄生组合式继承】
180207

181208
</script>
182209
</body>

0 commit comments

Comments
 (0)
X Tutup