Javascript inheritance — objects declared in constructor are shared between instances?

后端 未结 2 1656
故里飘歌
故里飘歌 2021-01-18 02:27

I am doing Object Oriented programming in JavaScript without Prototype/jQuery (I use jQuery for other stuff). It has been working fine so far, but I ran into an issue with i

2条回答
  •  孤城傲影
    2021-01-18 02:59

    B.prototype = new A();
    

    this creates only one instance of A for every B.

    You might consider doing sth like

    B = function()
    {
      this.$super = new A();
    }
    
    
    B.prototype.doStuff = function()
    {
      return this.$super(args);
    }
    
    
    C = function ()
    {
      this.$super = new B();
    }
    
    
    C.prototype.doStuff = function()
    {
      return this.$super(args);
    }
    
    C.prototype.whoIsMyGrandParent = function()
    {
      return this.$super.$super;
    }
    

    Javascript has NO real inheritation

提交回复
热议问题