• js的构造函数继承的几种类型


    function animale(){

             this.species ="猫科";

    }

    function cat(){

           this.name=name;  

           this.color=color

    }

    1:基于apply()方法和call()方法

    在子元素中加入一行代码

    function cat(){

          this.name=name;

          this.color=color;

          animale.apply(this,arguments);  //这里的this就是指当前调用对象

    }

    var cat1=new cat("大黄","白色");

    var cat2=new cat("戈薇","灰色");

    console.log(cat1.species);

    console.log(cat2.species);

    缺点:不能调用父类原型类中的方法和属性

    eg:animale.prototype.show=function(){alert(this.color)}

    cat1.show();>-----undefined

    2:基于原型的继承

    cat.prototype=new animale();  //定义玩这句后cat.prototype.constructor就指向了animale

    cat.prototype.constructor=cat;

    var cat3 =new cat("大黄","白色");

    var cat2=new cat("戈薇","灰色");

    console.log(cat2.species);

    //可以访问animale原型中的方法和属性,但是不能直接访问父类的构造函数,第一代改变了父类的引用类型的值,其他的子代也会改变,但基本类型的值不会随着改变。

    eg:cat3.species="犬科";

    console.log(cat2.species);   >-----猫科

    3:利用空媒介进行封装处理(基于直接用原型继承的改变)

    我们将不需要变化的数据放到父类 的原型里面

    animale.prototype.species="猫科"

    function f(){}   //空函数,F是空对象,所以几乎不占内存

    f.prototype=animale.prototype; 

    cat.prototype = new f();

    cat.prototype.constructor =cat;

    我们在把上述代码通过一个函数进行封装

    function excent(child,parent){

         var F=function(){}

         F.prototype=parent.prototype;

         child.prototype=new F();

         child.prototype.constructor=child;

    }

    excent(cat,animale);

    var cat1 = new Cat("大毛","黄色");

      alert(cat1.species); // 动物

  • 相关阅读:
    JSP学习(一)
    Servlet学习(五)——通过response设置响应体及中文乱码问题
    SQLServer -------- 不展示后两位小数
    MySQL ------ 数据库操作 (二)
    MySQL ------ CentOS 上 安装mysql (一)
    java ----------- I/O (六) 标准输入输出流
    java ----- I/O (五) 数据流读写文件
    Linux ------ centos 上安装JDK
    iis 中找不到安装的 .net 4.0
    清理C 盘
  • 原文地址:https://www.cnblogs.com/huagnchucai/p/6023308.html
Copyright © 2020-2023  润新知