方式1: 原型链继承

  1. function Supper() { //父类型
  2. this.superProp = 'The super prop'
  3. }
  4. //原型的数据所有的实例对象都可见
  5. Supper.prototype.showSupperProp = function () {
  6. console.log(this.superProp)
  7. }
  8. function Sub() { //子类型
  9. this.subProp = 'The sub prop'
  10. }
  11. // 子类的原型为父类的实例
  12. Sub.prototype = new Supper()
  13. // 修正Sub.prototype.constructor为Sub本身
  14. Sub.prototype.constructor = Sub
  15. Sub.prototype.showSubProp = function () {
  16. console.log(this.subProp)
  17. }
  18. // 创建子类型的实例
  19. var sub = new Sub()
  20. // 调用父类型的方法
  21. sub.showSubProp()
  22. // 调用子类型的方法
  23. sub.showSupperProp()

特点:这种继承方式的最大特点就是共享,所有实例共享原型对象中的所有属性和方法,
**

方式2、借用构造函数继承

  1. function Person(name, age) {
  2. this.name = name
  3. this.age = age
  4. }
  5. Person.prototype.setAge=function(age){
  6. this.age = age
  7. }
  8. function Student(name, age, price) {
  9. Person.call(this, name, age) // this.Person(name, age)
  10. this.price = price
  11. }
  12. var s = new Student('Tom', 20, 12000)
  13. console.log(s.name, s.age, s.price)

缺点只能继承父类实例的属性和方法,不能继承原型上的属性和方法

方式3、组合继承

  1. function Person(name, age) {
  2. this.name = name
  3. this.age = age
  4. }
  5. Person.prototype.setName = function (name) {
  6. this.name = name
  7. }
  8. function Student(name, age, price) {
  9. Person.call(this, name, age) //得到父类型的属性
  10. this.price = price
  11. }
  12. Student.prototype = new Person() //得到父类型的方法
  13. Student.prototype.constructor = Student
  14. Student.prototype.setPrice = function (price) {
  15. this.price = price
  16. }
  17. var s = new Student('Tom', 12, 10000)
  18. s.setPrice(11000)
  19. s.setName('Bob')
  20. console.log(s)
  21. console.log(s.constructor)
  • 优点:可以继承实例属性/方法,也可以继承原型属性/方法
  • 缺点:调用了两次父类构造函数,生成了两份实例


方式4、寄生组合继承(最优法)

  1. function inheritPrototype(subType, superType){
  2. var protoType = Object.create(superType.prototype); //创建对象
  3. protoType.constructor = subType; //增强对象
  4. subType.prototype = protoType; //指定对象
  5. }
  6. function SuperType(name){
  7. this.name = name;
  8. this.colors = ["red", "blue", "green"];
  9. }
  10. SuperType.prototype.sayName = function(){
  11. alert(this.name);
  12. }
  13. function SubType(name, age){
  14. SuperType.call(this, name);  //第二次调用SuperType()
  15. this.age = age;
  16. }
  17. // 方法1
  18. inheritPrototype(SubType, SuperType)
  19. // 方法2
  20. // SubType.prototype = Object.create(SuperType.prototype)//核心代码
  21. // SubType.prototype.constructor = SubType//核心代码
  22. SubType.prototype.sayAge = function(){
  23. alert(this.age);
  24. }
  25. var instance = new SubType("Bob", 18);
  26. instance.sayName();
  27. instance.sayAge();

inheritPrototype函数接收两个参数:子类型构造函数和超类型构造函数。
1. 创建超类型原型的副本。
2. 为创建的副本添加constructor属性,弥补因重写原型而失去的默认的constructor属性
3. 将新创建的对象(即副本)赋值给子类型的原型这种方法只调用了一次SuperType构造函数,instanceof 和isPrototypeOf()也能正常使用。