zoukankan      html  css  js  c++  java
  • 继承的几种模式


    // 继承方式1 ==> 默认的原型继承
    function Person() {}
    Person.prototype.run = function() {};
    var xiaohong = new Person();

    // 继承方式2 ==> 置换后的原型继承
    function Person() {}
    Person.prototype = {
    say: function() {}
    }
    var xiaohong = new Person();

    // 继承方式3 ==> 寄生式继承
    var obj = { val: 100 };
    var newObj = Object.create( obj );

    // 继承方式4 ==> 混入继承
    function extend( o1, o2 ) {
    for( var key in o2 ) {
    o1[key] = o2[key];
    }
    }
    var o = { abc: 888 };
    var o2 = { aaa: 111, bbb: 222, ccc: 333 };
    extend( o, o2 );

    // 继承方式5 ==> 对象冒充( 构造函数借用 )
    function Person( name, age, sex ) {
    this.name = name;
    this.age = age;
    this.sex = sex;
    }

    function Student( name, age, sex ) {
    this.Person = Person;
    this.Person( name, age, sex );
    delete this.Person;
    }

    function Student( name, age, sex ) {
    //Person.call( this, name, age, sex );
    Person.apply( this, arguments );
    }

    var xiaohong = new Student('小红', 16);
    console.log( xiaohong );

    // 继承方式6 ==> 原型组合继承
    function Person( name, age, sex ) {
    this.name = name;
    this.age = age;
    this.sex = sex;
    }

    Person.prototype = {
    run: function() {
    console.log('人都会跑');
    }
    };

    function Student( name, age, sex ) {
    Person.apply( this, arguments );
    }

    // 解决方案1:
    // 这样可以,但是不建议,因为一定会给Student添加一些额外的方法,
    // 这些方法不应该和Person共享
    //Student.prototype = Person.prototype;

    // 解决方案2,混入继承,可取,用的也比较多
    //extend( Student.prototype, Person.prototype );

    // 解决方案3,原型寄生组合式继承
    //Student.prototype = Object.create( Person.prototype );

    // 解决方案4,
    Student.prototype = new Person;

    // xiaofang ==> Student.prototype ==> Person.prototype ==> Object.prototype ==> null
    var xiaofang = new Student( '小芳', 17, '女' );
    xiaofang.run();


    /*
    * 理想的继承解决方案:
    * */
    function Person( name, age, sex ) {
    this.name = name;
    this.age = age;
    this.sex = sex;
    }

    Person.prototype = {
    run: function() {
    console.log('人都会跑');
    }
    };

    function Student( name, age, sex ) {
    Person.apply( this, arguments );
    }

    // 让学生实例,继承Student.prototype & Person.prototype
    Student.prototype = Object.create( Person.prototype );

    // 再给Student扩展自己独有的方法
    extend( Student.prototype, {

    } );

  • 相关阅读:
    201771030120-王嫄 实验三 结对项目—《西北师范大学疫情防控信息系统》项目报告
    201771030120-王嫄 实验二 个人项目—《西北师范大学学生疫情上报系统》项目报告
    201771030120-王嫄 实验一 软件工程准备 <课程学习目的思考>
    ETH充提币API接口中文文档
    开放API接口 USDT快捷接入充提教程
    比特币BTC支付API接口中文文档
    ERC20充提币API接口文档
    如何调用比特币钱包RPC API实现充值、转账、支付?
    .NET对接交易所钱包教程
    Java 对接交易所钱包解决方案
  • 原文地址:https://www.cnblogs.com/luxiaoxiao/p/6102977.html
Copyright © 2011-2022 走看看