让前端飞前端开发

web前端:谈谈js中实现类的创建和继承

2019-05-05  本文已影响8人  长肉肉呱

我们都知道,Javascript中是没有"类"这个概念的。但是在诸多环境中,有时又需要我们手动去实现类似java中的类和继承。下面我们来探索一下,如何才能完美实现js中的类和继承。

创建类

我们可以很简单的通过构造函数来实现一个类

// 创建类
        function Animal(name, sex) {
            this.name = name;
            this.sex = sex;
        }

        Animal.prototype.say = function() {
            console.log('i m animal');
        }

可以直接new出实现这个类的对象。

// 创建对象
        var cat = new Animal('cat', 'man');
        console.log(cat.name)
        console.log(cat.sex)
        console.log(cat.say())

实现继承

下面我们来谈谈js中类的继承。

        function Cat(name, sex) {
            Animal.call(this, name, sex);
        }

        Cat.prototype = new Animal;
        var maoxian = new Cat('maoxian', 'nv');
        maoxian.say();
        console.log(cat.name)
        console.log(cat.sex)
        console.log(cat.say())

介绍:在这里我们可以看到new了一个空对象,这个空对象指向Animal并且Cat.prototype指向了这个空对象,这种就是基于原型链的继承。
特点:基于原型链,既是父类的实例,也是子类的实例
缺点:无法实现多态继承

        function Cat(name) {
            Animal.call(this)
        }
        var maoxian = new Cat('maoxian');
        console.log(maoxian.name);
        console.log(maoxian.sex);
        maoxian.say()

特点:可以实现多继承
缺点:只能继承父类实例的属性和方法,不能继承原型上的属性和方法。

        function Cat(name){
        Animal.call(this);
        this.name = name || 'Tom';
        }
        Cat.prototype = new Animal();
        Cat.prototype.constructor = Cat;
        // Test Code
        var cat = new Cat();
        console.log(cat.name);
        console.log(cat.sleep());
        console.log(cat instanceof Animal); // true
        console.log(cat instanceof Cat); // true

特点:可以继承实例属性/方法,也可以继承原型属性/方法
缺点:调用了两次父类构造函数,生成了两份实例

        function Cat(name){
        Animal.call(this);
        this.name = name || 'Tom';
        }
        (function(){
        // 创建一个没有实例方法的类
        var Super = function(){};
        Super.prototype = Animal.prototype;
        //将实例作为子类的原型
        Cat.prototype = new Super();
        })();
        // Test Code
        var cat = new Cat();
        console.log(cat.name);
        console.log(cat.sleep());
        console.log(cat instanceof Animal); // true
        console.log(cat instanceof Cat); //true

其实类和继承在实战中用的很少,js毕竟不是基于类的语言,只是面试中有时会问到。有帮助的话给点个赞呗~~

上一篇 下一篇

猜你喜欢

热点阅读