JavaScript中实现继承

今天即兴研究了下JS,查阅了相关资料 ,发现Js中没有"子类"和"父类"的概念,也没有"类"(class)和"实例"(instance)的区分,全靠一种很奇特的"原型链"(prototype chain)模式,来实现继承。下面大概介绍一下Js中五种继承模式!

1、构造函数绑定:使用apply或是call
       

 function Animal() {
            this.species = "动物";
        }

        function Cat(name, color) {
            //Animal.apply(this, arguments);
            //Animal.call(this);
            this.color = color;
            this.name = name;
        }

        var cat1 = new Cat("cat1", "white");
        alert(cat1.species);


 2、prototype模式

      

      Cat.prototype = new Animal();
        //任何一个prototype对象都有一个constructor属性,指向它的构造函数.
        Cat.prototype.constructor = Cat;
        var cat1 = new Cat("大毛", "黄色");
        alert(cat1.species); // 动物

        //直接继承prototype   优点是效率比较高(不用执行和建立Animal的实例了),比较省内存。缺点是 Cat.prototype和Animal.prototype现在指向了同一个对象,那么任何对  
     Cat.prototype的修改,都会反映到Animal.prototype。
function Animal() { } Animal.prototype.species = "动物"; Cat.prototype = Animal.prototype; Cat.prototype.constructor = Cat;

3、利用空对象作为中介  F是空对象,所以几乎不占内存。这时,修改Cat的prototype对象,就不会影响到Animal的prototype对象。
     

   var F = function () { };
        F.prototype = Animal.prototype;
        Cat.prototype = new F();
        Cat.prototype.constructor = Cat;

        //对上面封装
        function extend(Child, Parent) {
            var F = function () { };
            F.prototype = Parent.prototype;
            Child.prototype = new F();
            Child.prototype.constructor = Child;
            Child.uber = Parent.prototype; //可以直接调用父对象的方法
        }

        extend(Cat, Animal);
        var cat1 = new Cat("大毛", "黄色");
        alert(cat1.species); // 动物


4、拷贝继承
      

  function extend2(Child, Parent) {
            var p = Parent.prototype;
            var c = Child.prototype;
            for (var i in p) {
                c[i] = p[i];
            }
            c.uber = p;
        }

5、 原型式继承
       

 //clone()函数用来创建新的类Person对象
        var clone = function (obj) {
            var _f = function () {
            };
            //这句是原型式继承最核心的地方,函数的原型对象为对象字面量
            _f.prototype = obj;
            return new _f;
        };
        //先声明一个对象字面量

        var Person = {
            name: 'Darren',
            getName: function () {
                return this.name;
            }
        };
        //不需要定义一个Person的子类,只要执行一次克隆即可
        var Programmer = clone(Person);
        //可以直接获得Person提供的默认值,也可以添加或者修改属性和方法
        alert(Programmer.getName());
        Programmer.name = 'Darren2';
        alert(Programmer.getName());
        //声明子类,执行一次克隆即可
        var Someone = clone(Programmer);

初步接触Javascript感觉挺简单,可是当我慢慢的深入其中,发现Javascript其实也是一门很复杂的语言!只有慢慢的深入了!

原文地址:https://www.cnblogs.com/tianboblog/p/3667889.html