javascript oop编程 — 实现继承的三种方式(1)

javascript oop编程 — 实现继承的三种形式(1)

(1)模拟类的方式, 我们都知道js是原型继承机制,不存在class和instance分离的这种方式
假设,我们有两个类

function  Animal(){
        this.name = “animal”;
        this.eat = function(){
                consle.log(“eating");
         }
}

function Cat(){
        this.say = function(){
                console.log(“miao miao!!");
         }
}

如果我们想要Cat 拥有Animal 的name属性和eat方法,只需要
Cat.prototype = new Animal();
但是这不是一个好的实践,想想看,如果还有一个Duck类,难道还要new一个Animal来继承吗,其他种种如此继续吗?如果Animal 构造函数需要传递参数呢? 
正确的作法是将通用的内容放到prototype里面,所有的子嗣,只需要将自己的prototype指向一个通用的prototype来实现继承。

如下,
Animal.prototype = {
        name:”animal”,
        eat:function(){
                console.log(“eating");
         }
}

Cat.prototype = Animal.prototype;

Object为我们提供了一个通用的继承函数(支持成都有差异),通过一个指定的原型创建一个对象
Object.create   很遗憾并不是所有浏览器都支持,手工改一下:

var inherit = Object.create || function(proto){
        function F(){};
        F.prototype = proto;
        return new F
}

于是上面的例子可以写成

Cat.prototype = inherit(Animal.prototype);
——————————
上面这样做,会出现Cat.prototype.constructor = F 的情况,我们需要拨乱反正,不如再写一个封装,专门来实现继承

var  extend = function(Child,Parent){
        Child.prototype = inherit(Parent.prototype);
        Child.prototype.constructor = Child;
}

很多第三方那个库的extend函数就是这么实现的