zoukankan      html  css  js  c++  java
  • 详解js中的寄生组合式继承

    寄生组合式继承是js中最理想的继承方式, 最大限度的节省了内存空间。

    js中的寄生组合式继承要求是:

          1.子对象有父对象属性的副本, 且这些不应该保存在子对象的prototype上.

          2. 子对象继承父对象prototype中全部的属性和方法, 且这些应该放保存在子对象的prototype上.

    来看下例子:

    //定义父对象
        function Father(name, age){
            this.name = name;
            this.age = age;
        }
        Father.prototype = {
            getName: function(){
               alert(this.name);
            },
            getAge: function(){
                alert(this.age);
            }
        }
        
    //定义子对象 function Son(sex, name, age){ this.sex = sex; Father.call(this, name, age); //继承Father的属性, 此处是一份副本 }
    //extend(子对象, 父对象)
    function extend(suberClass, superClass){ var object = function(o){ var F = function(){}; F.prototype = o; return new F(); }; //object作用就是拷贝一份父对象 suberClass.prototype = object(superClass.prototype); suberClass.prototype.constructor = suberClass; //强制constructor指向suberClass } extend(Son, Father); //执行函数 //继续为子类添加其它方法 Son.prototype.getSex = function(){ alert(this.sex); } //定义一个相同的方法, 屏蔽父对象的同名方法 Son.prototype.getName = function(name){ alert(this.name = name); }
    new Son('male', 'jack').getName('tom'); //'tom' new Father('jack').getName(); //'jack'
  • 相关阅读:
    koa2环境搭建
    单例模式
    nodejs fs path
    path node
    webpack code splitting
    babel 插件编写
    C#验证码类
    C#身份证识别相关技术
    C# Socket服务端与客户端通信(包含大文件的断点传输)
    动态抓取网页信息
  • 原文地址:https://www.cnblogs.com/tinkbell/p/3171818.html
Copyright © 2011-2022 走看看