一、原型链
使用实例方法时,会经历三个搜索步骤:
(1)搜索实例
(2)搜索SubType.prototype
(3)搜索SuperType.prototype
1 function SuperType() {
2 this.property = true;
3 }
4 SuperType.prototype.getSupperValue = function(){
5 return this.property;
6 };
7 function SubType(){
8 this.subproperty = false;
9 }
10 //继承SuperType
11 SubType.prototype = new SuperType();
12 SubType.prototype.getSubValue = function(){
13 return this.subproperty;
14 };
15
16 var instance = new SubType();
17 alert(instance.getSupperValue());
注:在通过原型链实现继承时,不能使用对象字面量创建原型方法,因为这样会重写原型链。其次,原型链实现继承时存在的问题和原型模式创建对象几乎一致,都是对于引用对象来说,这个问题就不详讲了。
二、借用构造函数
大家看代码应该就差不多可以理解借用构造函数实现继承了。这个方法主要的问题还是函数复用。
1 function SuperType(name) {
2 this.name = name;
3 }
4 function SubType(){
5 //继承了SuperType,同时还传递了参数
6 SuperType.call(this,"lily");
7 //实例属性
8 this.age = 21;
9 }
10
11 var instance = new SubType();
12 alert(instance.name);
13 alert(instance.age);
三、组合继承
组合继承避免了原型和借用构造函数的缺陷,融合了他们的有点,是最常用的继承模式。缺点:调用两次超类型构造函数。
1 function SuperType(name) {
2 this.name = name;
3 this.colors = ["red" , "blue"];
4 }
5 SuperType.protoType.sayName = function(){
6 alert(this.name);
7 };
8
9 function SubType(name , age) {
10 //继承属性
11 SuperType.call(this , name); //第二次调用SuperType()
12 this.age = age;
13 }
14 //继承方法
15 SubType.protoType = new SuperType(); //第一次调用SuperType()
16 SubType.protoType.constructor = SubType;
17 SubType.protoType.sayAge = function() {
18 alert(this.age);
19 };
20
21 var instance2 = new SubType("lily" , 21);
22 instance2.colors.push("black");
23 alert(instance2.colors); //red,blue,black
24 instance2.sayName() //lily
25 instance2.sayAge() //21
26
27 var instance3 = new SubType("lulu" , 22);
28 alert(instance3.colors); //red,blue
29 instance3.sayName() //lulu
30 instance3.sayAge() //22
四、寄生式继承
在主要考虑对象而不是自定义类型和构造函数的情况下,寄生式继承而是一种有用的模式。
1 function createAnother(original) {
2 var clone = Object(original); //通过调用函数创建一个新对象
3 clone.sayHi = function () { //以某种方式来增强这个对象
4 alert("hi");
5 };
6 return clone;
7 }
8 var person = {
9 name: "lily",
10 friends: ["q","a"]
11 };
12
13 var antherPerson = createAnother(person);
14 antherPerson.sayHi(); //hi
五、寄生组合式继承
这种继承被认为式引用类型最理想的继承范式。
1 function inheritPrototype(subType , superType) {
2 var prototype = Object(superType.prototype); //创建对象
3 prototype.constructor = subType; //增强对象
4 subType.prototype = prototype; //指定对象
5 }
6 function SuperType(name) {
7 this.name = name;
8 this.colors = ["red" , "blue"];
9 }
10 function SubType(name , age){
11 SuperType.call(this , name);
12 this.age = age;
13 }
14
15 inheritPrototype(SubType , SuperType);
16 SubType.prototype.sayAge = function(){
17 alert(this.age);
18 }
参考《JavaScript高级程序设计》