zoukankan      html  css  js  c++  java
  • JS中实现继承的六种方式及优缺点

    1、原型链继承

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

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

     

    优点:可以继承构造函数中的属性及方法  也可以继承原型对象中的属性及方法

    缺点:不能给父类的构造函数传参数

    function Father(){

    this.car="劳斯莱斯";

    }

    function Son(){

    this.phone="小米Max";

    }

     

    Son.prototype=new Father();//通过原型链继承

    var s=new Son();

    console.log("------:",s.car,s.phone);

    2、构造函数继承(对象冒充继承);

    优点:可以给父类的构造函数传参

    缺点:只能继承父类自身的属性和方法,原型对象上的不能继承

    function Parent(age){

    this.name="张三";

    this.age=age;

    }

    function Child(age){

    this.speak=function(){

    console.log("听我说说" ,this);

    }

    Parent.call(this,age);//对象冒充

    }

    var d=new Child(25);

    console.log("d:",d,d.name,d.age);

    d.speak();

     

    我们看到它解决了原型链继承的通病:

    1.避免了引用类型的属性被所有实例共享。

    2.可以在 Child 中向 Parent 传参。

    3、组合继承  原型继承+冒充继承

    function Parent(age){

    this.age=age;

    this.name=["zhang","wang","li"];

    }

    Parent.prototype.run=function(){

    console.log(this.name+" "+this.age);

    }

    function Child(age){

    this.speak=function(){

    console.log("我说说");

    }

    Parent.call(this,age);//对象冒充

    }

    Child.prototype=new Parent();//原型链继承

    var d=new Child(100);

    console.log("d:",d);

    d.speak();

    d.run();

    4、原型式继承

    创建的对象的原型=传入的对象

    function createObj(o){

     

            function Cat(){} //

         Cat.prototype = o;//-----  创建的对象的原型=传入的对象

          

         return new Cat();

    }

     

    var animal = {

    name:"cat",

    friend:["小白","小黑"]

    }

     

    var a = createObj(animal);

    console.log(a);

    5、寄生式继承

    function person (o) {

    var clone = Object.create(o);

    clone.sayName = function () {

    console.log('hello world');

    }

    return clone;

    }

     

    var obj = {

    name: '小黑',

    friends: ['A', 'B']

    }

     

    var p1 = person(obj)

    console.log(p1)

     

    //跟构造函数模式一样,每次创建对象都会创建一遍方法

    6、寄生组合式继承

    function Parent(name) {

    this.name = name;

    this.color = ['red', 'blue', 'yellow'];

    }

    Parent.prototype.getName = function() {

    console.log(this.name);

    }

    function Child(name) {

    Parent.call(this, name);  // 子类拥有父类的属性和方法

    }

    function createObj(o) {

    function F() {} // 创建对象

    F.prototype = o; // 创建对象的原型  =  obj(传入的对象)

    return new F();

    }

  • 相关阅读:
    第二部分 设计类型:第8章 方法
    centos7 网卡重命名
    centos7修改主机名
    修改umask值
    mysql表字段属性
    mysql基础操作
    mysql错误代码ERROR 1045 (转载)
    sed高级用法
    shell拷贝原文件到目标对应文件夹
    函数(位置传参)
  • 原文地址:https://www.cnblogs.com/A-Blingbling/p/14145270.html
Copyright © 2011-2022 走看看