zoukankan      html  css  js  c++  java
  • 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库如何实现继承的方法。

          

  • 相关阅读:
    Qt下如何修改文件的时间(全平台修改)
    Qt在windows 平台操作保存execel的表格(通过QAxObject来操作)
    VirtualTreeView控件
    VS2013设置release版本可调试
    工程脚本插件方案
    decode函数
    一个消息调度框架构建
    数据访问模式之Repository模式
    Angular.js Services
    OpenCascade简介
  • 原文地址:https://www.cnblogs.com/liuheng/p/6623093.html
Copyright © 2011-2022 走看看