js继承(一)原型继承

版权声明:转载声明原作者及链接 https://blog.csdn.net/ICY___/article/details/87473729

正式开工了

继承在js中有着很大的地位,同时理解起来也比较抽象,我将分几篇博客来记录js的继承。

原型继承:相当于将父类对象与子类对象打通桥梁,可以灵活实现追加属性与行为;

子类拥有父类的一切行为和属性。

 

特点:

非常纯粹的继承关系,实例是子类的实例,也是父类的实例

父类新增原型方法/原型属性,子类都能访问到

简单,易于实现

缺点:

要想为子类新增属性和方法,必须要在new Animal()这样的语句之后执行,不能放到构造器中无法实现多继承

创建子类实例时,无法向父类构造函数传参

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
        /*js里面的继承*/
        /*概念:继承的是对象   对象具有三大特征(封装,继承,多态)*/
        /*js里面如何去写继承*/
        /*实现继承:*/
        /*先去定义一个父类对象*/
        function Animal(){
            /*动物类有什么特征和行为*/
            this.name=null;
            this.AnimalColor=null;
            this.sex=null;
            this.age=null;
            this.type=null;
            this.sleep=function (){
                return this.name+"会睡觉";
            }
        }
        /*原型链追加(继承)  给原型方法里面追加属性和行为的*/
        Animal.prototype.eat=function (){
            return this.name+"会吃饭";
        }
        //定义一个子类对象
        function Cat(){
            this.soloMouse=function (){
                return this.name+"抓老鼠";
            }
        }

        /*1.原型链继承*/
         /*原理 将父类的实例作为子类的原型继承*/
        var a=new Animal();//实例对象
        Cat.prototype=a;
        Cat.prototype.speed=function (){
            return 5.0;
        }
        //实例化cat对象
        var c=new Cat();
        c.name="小花";
        c.type="猫科";
        c.AnimalColor="白家黑";
        c.age="2";
        c.sex="母";
       /* c.prototype.name="小黑";*/
        console.log(c);
        console.log(c.sleep());
        console.log(c.soloMouse());
        console.log(c.speed());
        console.log(c instanceof Cat);
        console.log(c instanceof Animal);


    </script>
</head>
<body>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/ICY___/article/details/87473729