Js面向对象构造函数继承

构造函数继承

  <!-- 创建构造函数 -->

  function Animal(){
    this.species= '动物';
  }
  function Dog(name,color){
    this.name = name;
    this.color = color;
  }

  prototype模式:

    如果"狗"的prototype对象,指向一个Animal的实例,那么所有"狗"的实例,就能继承Animal了。

  <!-- 继承 -->
  Dog.prototype = new Animal();
  Dog.prototype.constructor = Dog; //将Dog.prototype对象的constructor值改为Dog
  var dog1 = new Dog("大毛","黄色");
  alert(dog1.species); // 动物

  利用空对象作为中介:

    利用一个空对象作为中介。

  var F = function(){};
  F.prototype = Animal.prototype;
  Cat.prototype = new F();
  Cat.prototype.constructor = Cat;

  // F是空对象,所以几乎不占内存。这时,修改Cat的prototype对象,不会影响到Animal的prototype对象。

    我们将上面的方法,封装成一个函数,便于使用。

  function extend(Child, Parent) {
    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;
  }

  <!-- 使用的时候,方法如下 -->
    extend(Dog,Animal);
    var dog1= new Dog("大毛","黄色");
    alert(dog1.species); // 动物

    // 这个extend函数,就是YUI库如何实现继承的方法。

      

原文地址:https://www.cnblogs.com/liuheng/p/6623093.html