zoukankan      html  css  js  c++  java
  • javascript寄生组合式继承

      下面是javascript寄生组合式继承源代码,选自这里。讲解请见我所加注释:

    function creatObject(o){//该函数是为了创建原型链对象所用,传入值o为一个function F(){}//新建函数
    F.prototype = o;//设置该函数的原型属性为传入对象
    return new F();//调用该函数后返回链式对象F.prototype=o;
    }
    
    function inheritPrototype(subType, superType){//用于设置对象属性
    var prototype = creatObject(superType.prototype);   //创建对象相当于F.prototype=superType.prototype。注意此时var prototype存储为F对象
    prototype.constructor = subType;   //设置重写原型后的constructor:相当于F.constructor=subType
    subType.prototype = prototype; //设置subType原型:subType.prototype=F
    }
    
    function SuperType(name){//该函数是构造项,主要用于生成对象时变量的继承
    this.name = name;
    this.colors = ["red", "blue", "green"];
    }
    SuperType.prototype.sayName = function(){
    alert(this.name);
    };
    function SubType(name, age){//直接生成对象时的超类
    SuperType.call(this, name);//调用superType函数,设置name,colors[],sayName()属性。
    this.age = age;//直接设置age属性
    }
    inheritPrototype(SubType, SuperType);//调用函数,设置值,代码见上。未生成变量即完成设置
    SubType.prototype.sayAge = function(){//添加sayAge()属性。
    alert(this.age);
    };
    var instance1 = new SubType("Nicholas", 29);//新建变量,调用SubType() 构造器构造属性,其中调用SuperType()完成一系列继承变量初始化。
    instance1.colors.push("black");//此时colors属性为专有,因为其并未设置在原型中,而是通过SuperType()函数设置的。
    alert(instance1.colors);  //"red,blue,green,black"//后面神马的作对比的无关紧要了。
    instance1.sayName();  //"Nicholas";
    instance1.sayAge();   //29
       
    var instance2 = new SubType("Greg", 27);
    alert(instance2.colors);  //"red,blue,green"
    instance2.sayName();  //"Greg"
    instance2.sayAge();//  27

      好了,组合寄生式继承就像这个样子了。

  • 相关阅读:
    IDEA快速搭建 SpringCloud 注册中心与
    -bash: nginx: 未找到命令 (command not found) 解决方案
    【转载】02-PowerDesigner的下载及安装
    redis.conf配置文件配置项解析
    Linux 重启防火墙失败
    hduoj 3459 Rubik 2×2×2
    sdutoj 2605 A^X mod P
    hduoj 4710 Balls Rearrangement 2013 ACM/ICPC Asia Regional Online —— Warmup
    hduoj 4708 Rotation Lock Puzzle 2013 ACM/ICPC Asia Regional Online —— Warmup
    hduoj 4715 Difference Between Primes 2013 ACM/ICPC Asia Regional Online —— Warmup
  • 原文地址:https://www.cnblogs.com/stonl/p/4262944.html
Copyright © 2011-2022 走看看