#js继承

作者: 丶澎嘭嘭憉 | 来源:发表于2017-10-16 19:09 被阅读0次

    js继承的概念

    js里常用的如下两种继承方式:

    原型链继承(对象间的继承)
    类式继承(构造函数间的继承)

    类式继承是在子类型构造函数的内部调用超类型的构造函数。

    严格的类式继承并不是很常见,一般都是组合着用:

    function Super(){
        this.colors=["red","blue"];
    }
     
    function Sub(){
        Super.call(this);
    }
    

    原型式继承是借助已有的对象创建新的对象,将子类的原型指向父类,就相当于加入了父类这条原型链

    原型链继承

    为了让子类继承父类的属性(也包括方法),首先需要定义一个构造函数。然后,将父类的新实例赋值给构造函数的原型。代码如下:

    function Parent(){
            this.name = 'mike';
        }
    
        function Child(){
            this.age = 12;
        }
        Child.prototype = new Parent();//Child继承Parent,通过原型,形成链条
    
        var test = new Child();
        alert(test.age);
        alert(test.name);//得到被继承的属性
        //继续原型链继承
        function Brother(){   //brother构造
            this.weight = 60;
        }
        Brother.prototype = new Child();//继续原型链继承
        var brother = new Brother();
        alert(brother.name);//继承了Parent和Child,弹出mike
        alert(brother.age);//弹出12
    

    对象冒充

    function Cat(n) {
        this.name = n;
    }
    
    var obj = {};
    
    // obj 替代里面的this, 称为 对象冒充
    Cat.call(obj, "猫猫");
    
    // 猫猫
    console.log(obj.name);
    
    function Cat(a, b) {
        console.log(a, b);  
    }
    
    // call 的第1个参数,其实就是函数内部的this
    //        第2个参数,其实就是函数的第1个形参
    //        第3个参数,其实就是函数的第2个形参
    //        第4个参数,其实就是函数的第3个形参
    //        ... 依次顺延
    // Cat.call(null, "猫猫", "狗狗");
    
    // apply 的第1个参数,其实就是函数内部的this
    //        第2个参数,必须是数组
    //               数组的第1个元素  ,其实就是函数的第1个形参
    //               数组的第2个元素  ,其实就是函数的第2个形参
    Cat.apply(null, [1, 2]);
    

    相关文章

      网友评论

          本文标题:#js继承

          本文链接:https://www.haomeiwen.com/subject/wjpoyxtx.html