js继承的6种方式

http://www.cnblogs.com/ayqy/p/4471638.html

1.原型链
2.call继承 Fn.call(this) 将Fn中的this替换


    // 2.改进 不采用原生链 改变指向
    function Parent() {
        this.name ='xiaoer';
        this.arr = [1];
        this.say = function () {
            console.log('haha');
            return 10;
        }
    }
    function Child() {
        Parent.call(this)
    }
    // 那么创建的所有的子类的实例其实创建的相同于父亲的实例
    var c1 = new Child();
    var c2 = new Child();
    c1.name = 'sb';
    c1.arr.push(2);
    console.log(c1.arr);
    console.log(c2.name);
    console.log(c1.say());
    // 因为创建的是两个父亲的实例因此引用型的数据互补影响
    // 借父类的构造函数来增强子类实例,等于是把父类的实例属性复制了一份给子类实例装上了(完全没有用到原型)
    // 无法实现函数复用,每个子类实例都持有一个新的fun函数,太多了就会影响性能,内存爆炸。。

3.冒充对象继承

function Parent() {
       this.name = 'xiaoer';
       this.age = 10;
   }

   Parent.prototype.height = 20;

   function Child() {
       var temp = new Parent();
       for(var key in temp) {
           if (temp.propertyIsEnumerable(key)) {
               this[key] = temp[key];
           }
       }
       temp = null;
   }

   var p = new Child();

特点:父类私有的和共有的都可以拿到
4.混合模式继承

function Parent() {
        this.name = 'xiaoer';
        this.speak = function () {
            console.log('english');
        }
    }

    function Child() {
        Parent.call(this)
    }
    Child.prototype = new Parent();
  Child.constructor = Parent;
    var p = new Child();

特点:子类的私有和公有有2份属性 父类对象执行了2次
5.寄生组合模式继承

function Parent() {
        this.name = 'xiaoer';
    }
    Parent.prototype.height = 200;

    function Child() {
        Parent.call(this)
    }

    Child.prototype = Create(Parent.prototype);

    var p = new Child();

    
    function Create(o) {
        function Fn() {}
        Fn.prototype = o;
        return new Fn;
    }

特点: 子类不仅继承了父类的私有的方法,而且子类的原型也仅仅继承了父类原型的方法

  1. 中间类继承法 不兼容 直接更改原型指向
function haha() {

        arguments.__proto__ = new Array();

        arguments.reverse();

        console.log(arguments);
    }

    haha(1,34,'xs');
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言:了解熊师傅的朋友都知道,百度能查的到东西绝对不会提及太多,但是如果能按照思路仔细揣摩相信你一定不会后悔的,接...
    熊师傅阅读 666评论 1 3
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 7,885评论 2 17
  • 0 写在前面的话 大多数的面向对象编程语言中,比如C++和Java,在使用他们完成任务之前,必须创建类(class...
    自度君阅读 1,024评论 0 3
  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 4,130评论 3 11
  • build-ffmpeg.sh 脚本分析 脚本参数的判定 编译流程 待补充。。。 合并流程 lipo 流程拆出,单...
    zjunchao阅读 2,467评论 0 1