原型链是实现继承的主要方法,通过原型能让一个引用类型继承另一个引用类型。
1.原型链实现继承
function SuperType(){ this.superprop=1; } SuperType.prototype={ showSuperprop:function(){ console.log(this.superprop); } } function SubType(){ this.subprop=2; } SubType.prototype=new SuperType(); SubType.prototype.showSubprop=function(){ console.log(this.subprop); } var s=new SuperType(); s.showSuperprop();//1 var s2=new SubType(); s2.showSuperprop();//1 s2.showSubprop();//2
注意:在使用原型链实现继承时,不能用对象字面量方法创建原型方法。
2.借用构造函数
在子类型构造函数内部调用超类型的构造函数。
function SuperType(){ this.numbers=[1,2,3]; } function SubType(){ SuperType.apply(this); } var s=new SubType(); s.numbers.push(4); console.log(s.numbers);//1,2,3,4 var s1=new SubType(); console.log(s1.numbers);//1,2,3
* 3.组合继承--原型链结合借用构造函数
使用原型链实现对原型对象属性和方法的继承,使用构造函数实现对实例对象属性的继承。
function Person(name){ this.name=name; this.numbers=[1,2,3]; } Person.prototype.sayName=function(){ console.log(this.name); } function Student(name,age){ Person.call(this,name);////第二次调用Person() this.age=age; } Student.prototype=new Person();//第一次调用Person() Student.prototype.sayAge=function(){ console.log(this.age); } var s=new Student('小张',15); s.sayName();//小张 s.sayAge();//15 s.numbers.push(5); console.log(s.numbers);//[1, 2, 3, 5] var s1=new Student('小兰',14); s1.sayName();//小兰 s1.sayAge();//14 console.log(s1.numbers);//[1, 2, 3]
组合继承是很常用的继承方式,但是它也有个缺点,就是需要调用两次超类型的构造函数。
*4.寄生式组合式继承
寄生组合式继承:借用构造函数继承属性,使用原型链的混合型式继承方法。寄生组合式是实现继承的最佳方式。
function object(o) { function F() { } F.prototype = o; return new F(); } function inheritPrototype(superType, subType) { var prototype = object(superType.prototype); prototype.constructor = subType; subType.prototype = prototype; } function superType(name) { this.name = name; } superType.prototype.sayName = function () { console.log('my name is ' + this.name); } function subType(name, age) { superType.call(this, name); this.age = age; } inheritPrototype(superType, subType); subType.prototype.sayAge = function () { console.log('my age is ' + this.age); } var s=new superType('Cathy'); s.sayName();//my name is Cathy var s1 = new subType('Tom', 18); s1.sayName();//my name is Tom s1.sayAge();//my age is 18