面试必问之继承

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);
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容