js继承的几种方式
要了解js继承,必定先要去了解原型链,为何呢?因为原型链是作为实现继承的主要方法。
以下几点一定要谨记:那就是什么是构造函数、什么是原型、什么是实例、以及他们之间的关系?
继承:利用原型让一个引用类型继承另一个引用类型的属性和方法
每个构造函数都有一个原型对象:Person.prototype(prototype是指向原型对象的指针)
原型对象都包含一个指向构造函数的指针:Person.prototype.constructor = Person
实例都包含一个指向原型对象的内部指针:var a = new Person();a._proto_ = Person.prototype
通过原型链实现继承
function SuperType(){ this.colors = ["red","blue","green"]; } function SubType(){} SubType.prototype = new SuperType(); var instance = new SubType(); instance.colors.push("white"); console.log(instance.colors); //"red,blue,green,white" var instance2 = new SubType(); console.log(instance2.colors); //"red,blue,green,white"
借用构造函数
function SuperType(name){ this.name = name; } function SubType(){ SuperType.call(this,"Lucy"); this.age = 20; } var instance = new SubType(); console.log(instance.name); //Lucy console.log(instance.age); //20
组合继承
组合继承也叫作伪经典继承,指的是将原型链和借用构造函数的技术组合在一起的继承模式,精髓是使用原型链实现对原型属性和方法的继承,通过借用构造函数来实现对实例属性的继承。
function SuperType(name){ this.name = name; this.colors = ["red","blue","green"]; } SuperType.prototype.sayName = function(){ console.log(this.name); } function SubType(name,age){ SuperType.call(this,name); this.age = age; } SubType.prototype = new SuperType(); SubType.prototype.sayAge = function(){ console.log(this.age); } var instance = new SubType("Lucy",20); instance.colors.push("white"); console.log(instance.colors); //"red,blue,green,white" instance.sayName(); //Lucy instance.sayAge(); //20 var instance2 = new SubType("Tom",28); console.log(instance2.colors); //"red,blue,green" instance2.sayName(); //Tom instance2.sayAge(); //28