zoukankan      html  css  js  c++  java
  • JS继承几种方式

    1、原型继承
    <script>
    function Person(name,age){
    this.name = name;
    this.age = age;
    }
    Person.prototype.sayHello = function(){
    alert("使用原型得到Name:"+this.name);
    }
    var per = new Person("dzk",21);
    per.sayHello();//输出:使用原型得到Name:dzk

    function Student(){}
    Student.prototype = new Person("gw",22);
    var stu = new Student();
    Student.prototype.grade = 5;
    Student.prototype.intr=function(){
    alert(this.grade);
    }
    stu.sayHello();//输出:使用原型得到Name:gw
    stu.intr();//输出:5
    </script>
    优点:
    1、非常纯粹的继承关系,实例是子类是实例,也是父类的实例,如上stu
    2、父类新增原型方法or原型属性,子类都能访问到
    3、简单、易于实现
    缺点:
    1、无法实现多继承
    2、来自原型对象的引用属性是所有实例共享的

    2、构造函数继承
    <script>
    function Parent(name){
    this.names = name;
    this.sayParent=function(){
    alert("Parent:"+this.names);
    }
    }
    function Child(name,age){
    this.tempfds = Parent;
    this.tempfds(name);
    this.age = age;
    this.sayChild=function(){
    alert("Child"+this.names+"age:"+this.age);
    }
    }

    var parent=new Parent("江剑臣");    
    parent.sayParent(); //输出:“Parent:江剑臣”  
        var child=new Child("李鸣",24);
        child.sayChild();  //输出:“Child:李鸣 age:24”  
    </script>
    优点:
    1、解决了1中,子类实例共享父类引用属性的问题
    2、可以实现多继承
    缺点:
    1、实例并不是父类的实例,只是子类的实例
    2、无法实现函数复用,每个子类都有父类实例函数的副本,影响性能

    3、Call、apply实现继承
    <script>
    function Person(name,age,love){
    this.name = name;
    this.age = age;
    this.love = love;
    this.say=function(){
      alert("姓名:"+name);  
    }
    }
    //call方式
    function Student(name,age){
    Person.Call(this,name,age);
    }
    //apply方式     
    function teacher(name,love){  
            //Person.apply(this,[name,love]);  
            Person.apply(this,arguments); //跟上句一样的效果,arguments  
        }  

        //call与aplly的异同:  
        //1,第一个参数this都一样,指当前对象  
        //2,第二个参数不一样:call的是一个个的参数列表;apply的是一个数组(arguments也可以)  

        var per=new Person("武凤楼",25,"魏荧屏"); //输出:“武凤楼”  
        per.say();  
        var stu=new student("曹玉",18);//输出:“曹玉”  
        stu.say();  
        var tea=new teacher("秦杰",16);//输出:“秦杰”  
        tea.say();  

    </script>

  • 相关阅读:
    STM32---GPIO
    SQLITE笔记
    STM32 ---- PWM
    STM32--- IIC使用
    TP配置apache下Rewrite模式
    韩顺平老师SNS数据库表 http://blog.csdn.net/zxman660/article/details/7786994
    HashMap和HashTable的区别http://blog.csdn.net/shohokuf/article/details/3932967
    HashMap和HashSet的区别http://www.importnew.com/6931.html
    在mysql中存储生日,php中计算今天是否为用户生日
    文件的MIME类型
  • 原文地址:https://www.cnblogs.com/xiaoweigogo/p/7803214.html
Copyright © 2011-2022 走看看