zoukankan      html  css  js  c++  java
  • Js继承小结

    Js继承小结

    一直以来,对Js的继承有所认识,但是认识不全面,没什么深刻印象。于是,经常性的浪费很多时间重新看博文学习继承,今天工作不是特别忙,有幸看到了http://www.slideshare.net/stoyan/javascript-patterns?from_search=9 (该博文作者同样是《Javascript Patterns》一书的作者,效力于Yahoo,是YSlow 的架构者和smush.it的作者),在此,自己做一些小结和笔录以免多次重复学习。

    js继承:

    /*******继承1:复制父亲对象所有属性-->子对象**********/
    function extend(parent, child){
    var child = child || {};
    for(var prop in parent){
    child[prop] = parent[prop];
    }
    return child;
    }

    /*******混合继承:从多个对象中继承****************/
    function mixInThese(){
    var args = arguments,
    child = {};
    for(var i = 0, len = args.length; i < len; i++){
    for(var prop in args[i]){
    child[prop] = args[i][prop];
    }
    }
    return child;
    }
    var cake = mixInThese(

           {"oil": 3, "button": 4},

           {"weight": 34},

          {"tasty": "sweet"});
    console.log(cake);

    /*************经典继承 原型继承 ES标准推荐 继承方式1***************************/
    function inherit(parent, child){
    child.prototype = new Parent(); 
    }

    /**********借用构造函数    继承方式2********/
    function Child(){
    Parent.apply(this, arguments);
    //anything else
    }

    优点:创建对象的时候,可以传递参数到父亲对象

    缺点:没有继承Prototype原型链上的属性

    /*****************/

    /***********借用构造函数 + 原型继承 继承方式3*****************/
    function Child(){
    Parent.apply(this, arguments);
    }
    Child.prototype = new Parent();

    /**************父子对象共用同一份prototype*  继承方式4*********************************/
    function inherit(parent, child){
    child.prototype = child.prototype;
    };

    优点:父子对象共用同一份prototype

    缺点:父子对象共用同一份prototype

    /***********只继承prototype上的属性(父子对象不共用同一份prototype) 继承方式5************/
    function inherit(parent, child){
    function F(){}
    F.prototype = new parent();
    child.prototype = new F();

    child.uber = parent.prototype;

    child.prototype.constructor = child;
    }

    基于原型的继承总结:

    1.没有像类(Class-Like)一样的构造函数.

    2.对象和对象之间直接通过原型实现继承(而不像其他语言中的类和类之间的继承)。

     
     
     
    标签: js继承
  • 相关阅读:
    2-10 案例4:像素读取写入
    2-8 案例3:不同图片质量保存
    2-7 案例2:图片写入
    Linux文件操作实用笔记
    Linux文件操作实用笔记
    Linux 文件系统基础
    Linux 文件系统基础
    一篇故事讲述了计算机网络里的基本概念:网关,DHCP,IP寻址,ARP欺骗,路由,DDOS等...
    一篇故事讲述了计算机网络里的基本概念:网关,DHCP,IP寻址,ARP欺骗,路由,DDOS等...
    30 个与程序猿有关的成语
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3165803.html
Copyright © 2011-2022 走看看