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

    javascript有很多种继承方法,今天我简单的总结一下:

    一、原型继承方式:
    1    function parent(){};
    2            parent.prototype.Pname='Parent';
    3    function child(){}
    4           child.prototype=new parent();                 //将子类的原型指向父类
    5           child.prototype.Cname='child';

    这样就实现了原型继承。将父类的对象作为子类的原型;

    打开调试器:粘贴上面的代码。然后var c = new child(); console.log(c);我们可以看到输出: child {Cname: "child", Pname: "Parent"}

    二、 组合继承:
     1   function parent2(sparam){
     2             this.param=sparam;
     3             this.getParam=function(){
     4                return this.param;
     5            }
     6    };
     7 
     8   function child2(cparam,cname){
     9                  parent2.call(this,cparam);                   //调用父类构造函数
    10                  this.name=cname;
    11    }
    12   child2.prototype=new parent2('param');                //继承父类
    13  child2.prototype.getName=function(){
    14         return this.name;
    15     }

    用call和apply的方式将this指针传给父方法。

    三、类继承不是很常见,一般都是组合着用。看下例:

    1 function Super(){
    2     this.colors=["red","blue"];
    3 }
    4  
    5 function Sub(){
    6     Super.call(this);
    7 }

    这就是类式继承,这个有一个缺点就是   方法在构造函数内创建,函数的复用就无从谈起了,而且还有一个问题,就是在超类原型中定义的方法对子类是不可见的。

    还有就是子类会复制父类的属性,如下:

    1 var a=new Sub();
    2 a.colors.push("black");
    3 console.log(a.colors);//----->   "red,blue,black"
    4  
    5 var b=new Sub();
    6 console.log(b.colors);//----->   "red,blue"


    三、属性复制:

    遍历父类的属性,复制给子类。



  • 相关阅读:
    PHP __get和__set的理解
    PHP new self()和new static()的区别探究
    PHP 配置默认SSL CA证书
    PHP Trait超类总结
    PHP abstract 抽象类定义与用法示例
    php implements的作用和总结
    PHP性能优化利器:生成器 yield理解
    PHP 生成不重复唯一标识 session_create_id()
    【SpringBoot】SpringBoot源码编译
    【Redis】分布式锁之Redis实现
  • 原文地址:https://www.cnblogs.com/webARM/p/4161556.html
Copyright © 2011-2022 走看看