zoukankan      html  css  js  c++  java
  • js中几种继承的简单总结

    继承

    • 我们都知道子承父业叫做继承,那在js中什么是继承呢?继承:只要某个对象使用了自己没有而另一个对象有的功能就叫继承,以下是几种继承方式:

    1,构造函数继承

    • 构造函数继承又叫做改变this指向的继承,只能继承构造函数this的属性和方法,不能继承原型身上的属性和方法
    function Parent(num){
        this.num = num;
        this.show = function(){
            alert("这是数字"+this.num);
        }
    }
    function Child(num1){
        //Father.call(this,num1);//call适合固定参数的继承
        //Father.apply(this,arguments);//apply适合不定参数的继承
    }
    var p = new Parent(10);
    var c = new Child(1);
    p.show()
    c.show();
    

    2,原型对象继承

    • 原型对象继承只能继承原型的属性和方法,不能继承构造函数this身上的属性和方法
    function Parent(){
        this.num = 2;
    };
    Parent.prototype.init = function(){
        console.log("hello world")
    }
    function Child(){};
    //Child.prototype = Parent.prototype;
    //但是要注意对象的深浅拷贝
    for(var i in Parent.prototype){
        Child.prototype[i] = Parent.prototype[i];
    }
    Child.prototype.init = function(){
        console.log("这是修改之后的")
    }
    var p = new Parent()
    p.init()
    var c = new Child()
    c.init();
    

    3,原型链继承

    • 原型链继承,既能继承原型身上的属性和方法,又能继承构造函数中的this的属性和方法但是不方便传参
    function Parent(num){
        this.num = num;
    }
    Parent.prototype.init = function(){
        console.log("hello")
    }
    function Child(n){}
    Child.prototype = new Parent(520);
    Child.prototype.init = function(){
        console.log("html")
    }
    var p = new Parent(3.1415);
    p.init()
    console.log(p.num)
    var c = new Child();
    c.init();
    console.log(c.num);
    

    4,混合继承

    • 混合继承,使用call或apply继承父类的构造器中的内容,使用原型继承,继承父类的原型,是常用继承方式之一
    function Parent(name, age){
        this.name = name;
        this.age = age;
    }
    Parent.prototype.init = function(){
        alert(this.name + "的年龄是" + this.age + "岁");
    }
    
    function Child(){
        Parent.apply(this,arguments);
    }
    //如果不做Child的原型继承Parent的原型,此时会报错:Child.show is not a function
    for(var i in Parent.prototype){
        Child.prototype[i] = Parent.prototype[i];
    }
    Child.prototype.init = function(){
        alert("我是son,我的年龄是"+this.age + "岁");
    }
    var p = new Parent("张三","33");
    var c = new Child("李四","10");
    p.init();
    c.init();
    

    5,ES6 class继承

    • class继承具有改变this指向的特性和原型链继承的特点,是常用继承方式之一
    class Parent{
        constructor(){
        }
        show(){
        }
    }
    class Child extends Parent{
        constructor(){
            super()
        }
        show(){
        }
    }
    
  • 相关阅读:
    Men and women can't be 'just friends
    thin-provisioning-tools
    自签名证书
    sqlite manager
    python -m SimpleHTTPServer 80801
    rsa or dsa?
    sl4a
    mtp
    sl4a
    基站记录仪是个啥?
  • 原文地址:https://www.cnblogs.com/tongmeng/p/11789159.html
Copyright © 2011-2022 走看看