Constructors in JavaScript objects

后端 未结 19 1983
夕颜
夕颜 2020-11-22 10:21

Can JavaScript classes/objects have constructors? How are they created?

19条回答
  •  迷失自我
    2020-11-22 10:41

    While using Blixt's great template from above, I found out that it doesn't work well with multi-level inheritance (MyGrandChildClass extending MyChildClass extending MyClass) – it cycles on calling first parent's constructor over and over. So here is a simple workaround – if you need multi-level inheritance, instead of using this.constructor.super.call(this, surName); use chainSuper(this).call(this, surName); with the chain function defined like this:

    function chainSuper(cls) {
      if (cls.__depth == undefined) cls.__depth = 1; else cls.__depth++;
      var depth = cls.__depth;
      var sup = cls.constructor.super;
      while (depth > 1) {
        if (sup.super != undefined) sup = sup.super;
        depth--;
      }
      return sup;
    }
    

提交回复
热议问题