美文网首页
面试必问之继承

面试必问之继承

作者: 前端陈晨 | 来源:发表于2019-02-05 23:51 被阅读0次

js继承常用的三种方法,记录一下,马上要面试了。

觉得有用可以帮我点个赞吗?谢谢了。

    // 原型链继承
    function Parent() {
      this.name = '原型链继承';
      this.play = [1,2,3];
    }
    Parent.prototype.getName = function () {
      console.log(this.name);
    }

    function Child() {
      this.type = '原型链继承child';
    }
    Child.prototype = new Parent();
    // 原型链上的原型对象是通用的,改变一个,其他的都会改变,但我们不想所有对象都改变
    var child1 = new Child();
    var child2 = new Child();
    child1.play.push(4)
    console.log(child1.play)
    console.log(child2.play)
    // 构造函数继承
    function Parent() {
      this.name = '构造函数继承';
      this.play = [1,2,3];
    }
    Parent.prototype.getName = function () {
      console.log(this.name);
    }

    function Child() {
      Parent.call(this)
      this.type = '构造函数继承child';
    }

    var child1 = new Child();
    console.log(child1.getName)
    //构造函数继承不会继承原型链上的方法
    // 组合继承
    // 原理:创建中间对象,中间对象的原型对象是父类的
    function Parent() {
      this.name = '组合继承';
      this.play = [1,2,3];
    }
    Parent.prototype.getName = function () {
      console.log(this.name);
    }

    function Child() {
      Parent.call(this)
      this.type = '组合继承child';
    }
    Child.prototype = Object.create(Parent.prototype);
    Child.prototype.constructor = Child;
    //没有这句代码,Child.prototype.constructor会指向Parent
    var child = new Child()
    console.log(child instanceof Child,child instanceof Parent);
    console.log(child.constructor);

相关文章

  • 面试必问之继承

    js继承常用的三种方法,记录一下,马上要面试了。 觉得有用可以帮我点个赞吗?谢谢了。

  • 2020-01-19做些js的数组练习吧

    1.前端面试必问之数组去重 前端面试必问之数组去重 2.前端面试必问之深拷贝浅拷贝 3.

  • 面试必问之HashMap

    大家都知道,HashMap 的底层在 JDK 1.7 的时候为数组+链表,在JDK 1.8的时候为数组+链表+红黑...

  • 面试必问

    方法重载 :不属于多态方法重写 :属于多态构造器: 构造器名称跟类名一样面向对象思想的三大特点:多态、封装、继...

  • 面试必问之JVM原理

    1:什么是JVM JVM是Java Virtual Machine(Java虚拟机)的缩写,JVM是一种用于计算设...

  • 面试必问之JVM原理

    1:什么是JVM JVM是Java Virtual Machine(Java虚拟机)的缩写,JVM是一种用于计算设...

  • 前端面试必问:javascript原型和继承

    如题,准备面试一次就看一次,索性自己好好总结一下吧,一劳永逸。 本文从以下几个方面着手 0怎么理解面向对象 1创建...

  • 面试必问--JSONP

    json+padding = JSONPJSON格式:{ 'a': xxx,'b':yyy }JSONP格式类似于...

  • RecyclerView面试必问

    RecyclerView是谷歌官方出的一个用于大量数据展示的新控件,可以用来代替传统的ListView,更加强大和...

  • 前端面试必问之Webpack

    概念 打包你的资源,webpack是把项目当作一个整体,通过一个给定的的主文件,webpack将从这个文件开始找到...

网友评论

      本文标题:面试必问之继承

      本文链接:https://www.haomeiwen.com/subject/vbrbsqtx.html