JavaScript面试题总结系列(五)

5.JavaScript继承

继承是什么

A对象通过继承B对象,就能直接拥有B对象的所有属性和方法。

方式一、原型链继承

核心:子类型的原型为父类型的一个实例对象

    // 创建一个父类(注意其本质仍然是一个构造函数)
    function Parent() {
        this.name='kevin';
    }

    // 创建父类上的一个共享方法
    Parent.prototype.getName = function(){
        console.log(this.name);
    }

    // 创建子类
    function Child() {

    }

    // 核心代码:将父类的实例作为子类的原型
    Child.prototype = new Parent();
    
    var child1 = new Child();

    console.log( child1.getName() ); // kevin

方式二、组合继承优化

核心:借助已有的对象来创建对象,var B = Object.create(A); ,以A对象为原型,创建B对象。B继承了A对象的所有属性和方法。

        // 创建父类
        function Person(name,age) {
            this.name = name;
            this.age = age;
        }

        // 创建父类共享的方法
        Person.prototype.setAge = function(){
            console.log(111);
        }

        // 创建子类
        function Student(name, age, price) {
            Person.call(this, name, age);
            this.price = price;
            this.setScore = function() {

            }
        }

        Student.prototype = Object.create(Person.prototype); // 核心代码
        Student.prototype.constructor = Student; // 核心代码

        var s1 = new Student('tom', 20, 15000);

        console.log(s1 instanceof Student); // true
        console.log(s1 instanceof Person); // true

        console.log(s1.constructor); // Student
        console.log(s1); // Student {name: "tom", age: 20, price: 15000, setScore: ƒ}

小结:

总结该专题知识点的时候,找到了很多好的资源,讲的基本都是六-八种的继承方式。这里没有一一列出的原因是希望如果赶时间参加面试的你,可以先从这两种根本的方法去下手,有一个初步的了解,不至于问到的时候一点都不知道。

方式一是一种最基础,最接近于常识的理解,有助于快速进入状态。方式二则是比较了几种实现的继承的方式后,一种相对来说比较完美的做法,可以作为一个“终极”继承版本来用。有兴趣的读者,可以看看文末的链接,获取更多的继承方式的讲解。


参考链接:
https://github.com/mqyqingfeng/Blog
https://segmentfault.com/a/1190000016708006
https://segmentfault.com/a/1190000015727237
https://juejin.im/post/5bcb2e295188255c55472db0#heading-0
https://www.cnblogs.com/humin/p/4556820.html
https://github.com/mqyqingfeng/Blog/issues/16
http://www.ayqy.net/blog/%E9%87%8D%E6%96%B0%E7%90%86%E8%A7%A3js%E7%9A%846%E7%A7%8D%E7%BB%A7%E6%89%BF%E6%96%B9%E5%BC%8F/
https://zhuanlan.zhihu.com/p/37735247

猜你喜欢

转载自www.cnblogs.com/zxxsteven/p/11737351.html