• 继承的几种模式



    // 继承方式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, {

    } );

  • 相关阅读:
    linux 经常使用网络命令
    ExtJS学习--------Ext.Element中其它操作方法学习
    对“使用MyEclipse,写的jsp代码因有汉字而无法保存”问题的解决
    SQL之case when then用法
    SQL之CASE WHEN用法详解[1]
    [SQL case when的两种用法]
    在delphi中生成GUID
    在delphi中生成GUID/自动获取临时表名......
    Delphi中Owner和Parent的区别
    Delphi处理数据网格DBGrid的编辑框 获取还没有提交到数据集的字段文本
  • 原文地址:https://www.cnblogs.com/luxiaoxiao/p/6102977.html
Copyright © 2020-2023  润新知