JS 继承

一、继承的作用

    1.子对象继承父对象

    2.代码重用

    eg:》分析属性及行为

          》提取一个通用的大模板,然后这些特殊的东西去继承这个模板

          》业务上的关系:上下级关系

         》代码上的关系:不用重复写共同的属性,提高代码重用

二、继承的方式

   call ;apply ;prototype; for in 

   2.1 Call

<script>
    function  plane(blood,speed) {
        this.blood=blood;
        this.imageNode=document.createElement("img");
        this.speed=speed;
        this.x=10;
        this.y=10;
        this.isDie=false;
        this.move=function () {
            console.log("飞机移动")
        }
    }
    function smallPlane(blood,speed) {
        plane.call(this,blood,speed);//继承了plane这个模板,参数是从这个函数中传过来的
        //**这里的call需要放在函数的第一行
        this.move=function () {
            console.log("小飞机移动")
        };
        this.shot=function () {

        }
    }
    var small=new smallPlane(4,5);
small.move();//大飞机移动 
console.log(small);//smallPlane {blood: 4, imageNode: img, speed: 5, x: 10, y: 10…} </script>

  2.2 apply 

 与call方法不同之处在于apply传的参数:

    

plane.apply(this,[blood,speed]);//这里传的是一个数组,数组中包含所有的参数

  也可以写成下面这样:

plane.apply(this,arguments);//arguments代表一个参数列表,里面就是调用该方法的时候传进来的参数

  方法重写:

function bigPlane() {
        plane.apply(this,arguments);
        //方法的重写 overwrite;因为在模板中有move这个函数,但是实体大飞机和模板的move方法不一样,需要重写定义,故名方法重写
        this.move=function () {
            console.log("大飞机移动")
        };
    }
    var Big=new bigPlane();//bigPlane {blood: undefined, imageNode: img, speed: undefined, x: 10, y: 10…}
    console.log(Big);//大飞机移动
    Big.move();

  

   2.3 prototype

 

原文地址:https://www.cnblogs.com/potato-lee/p/6560013.html