zoukankan      html  css  js  c++  java
  • JavaScript的继承

    1.借用构造函数继承 call,apply(继承实例属性)

    function Parent(sName,nAge){
        this.sName = sName;
        this.nAge = nAge;
    }
    
    function Child(sName,nAge,sSex){
        //Parent.call(this,sName,nAge);
        Parent.apply(this,[sName,nAge]);
        this.sSex = sSex;
    }

    2.原型继承

    利用空函数做中介(YUI做法)

    //ES3
    function fExtend(Child,Parent){
        var F = function(){};
        F.prototype = Parent.prototype;
        Child.prototype = new F();
        Child.prototype.constructor = Child;
    }   
    //ES5
    Object.create(new Parent(),{props}) //简单,多new了一个parent对象
    //避免new对象
    function Child(){
        Parent.call(this);//实例继承
    }
    Child.prototype = Object.create(Parent.prototype);//object create只进行原型继承

    3.拷贝继承

    深拷贝继承(jquery做法)

    function fDeepCopy(dest,src){
        var dest = dest || {},
            toString = Object.prototype.toString;
        for(var p in src){
            if(toString.call(p) === '[object Object]'){
                dest[p] = {};
                fDeepCopy(p,dest[p]);
            }
            else if(toString.call(p) === '[object Array]'){
                dest[p] = [];
                fDeepCopy(p,dest[p]);
            }
            else{
                dest[p] = src[p];
            }
        }
    }
    
    fDeepCopy(Child,Parent);//实例属性拷贝
    fDeepCopy(Child.prototype,Parent.prototype);//原型属性拷贝

    4. class继承(ES6)

    class Animal {
        constructor(){
            this.type = 'animal';
        }
        says(text){
            console.log(this.type + ' says ' + say)
        }
    }
    
    class Cat extends Animal{
        constructor(){
            super();
            this.type = 'cat';
        }
    }
    
    const cat = new Cat();
    cat.says('hello');//cat says hello

     总结:一般完整的继承要由借用继承和原型继承来组合完成,借用继承负责实例属性,包括引用类型的属性,原型继承一般负责原型上的方法继承,原型属性为引用类型的话,会被共用。ES6的话,直接用class继承即可。

  • 相关阅读:
    计算1至n中数字X出现的次数
    DOM处理
    SQL Server中日志
    怎样玩转千万级别的数据
    协议的分用以及wireshark对协议的识别
    序列化json对象,通过ajax传入asp.net mvc后台
    新时代的Vim C++自动补全插件 clang_complete
    ASP.NET Web API 接口执行时间监控
    应用之星在线app开发平台,菜鸟也会做应用
    1.11 查找空值
  • 原文地址:https://www.cnblogs.com/mengff/p/5005597.html
Copyright © 2011-2022 走看看