Search code examples
javascriptoopextendjavascript-objects

Why my extend() method in Javascript don't work for 3 and more objects?


I have 3 object.

netBuilder Numbering NumberingMethodDefault

And i have some extend method.

extend: function (Child, Parent) {
  var F = function () {};
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.prototype.constructor = Child;
  Child.superclass = Parent.prototype;
  this.mixin(Child, Parent);
},
/**

 * @param {type} dst
 * @param {type} src
 * @returns {undefined}
 */
mixin: function (dst, src) {
  var tobj = {};
  for (var x in src) {
    if ((typeof tobj[x] == "undefined") || (tobj[x] != src[x])) {
      dst[x] = src[x];
    }
  }
  if (document.all && !document.isOpera) {
    var p = src.toString;
    if (typeof p == "function" && p != dst.toString && p != tobj.toString &&
      p != "\nfunction toString() {\n    [native code]\n}\n") {
      dst.toString = src.toString;
    }
  }
}

Than i try that Numbering extends from netBuilder and NumberingMethodDefault extends from Numbering.

oopUtility.extend(Numbering, netBuilder);
oopUtility.extend(NumberingMethodDefault, Numbering);

And call superclassses

Numbering.superclass.constructor.call(this, arguments);
NumberingMethodDefault.superclass.constructor.call(this, arguments);

Numbering has method setNumber(). I have access in Numbering to netBuilder methods, but in NumberingMethodDefault i can't execute method setNumber() from Numbering.

Uncaught TypeError: Object #<NumberingMethodDefault> has no method 'setNumber'

Than i console.log() what is superclass for NumberingMethodDefault

console.log(NumberingMethodDefault.superclass);
//and it was netBuilder, not Numbering! о_О

How can i make it work. I need extend for 3 or more objects!


Solution

  • This is because your call to mixin manually copies properties from one object to the other, and is overwriting the .superclass assignment. If you're emulating class inheritance you won't need mixins in this way, so remove that code altogether and you shouldn't have a problem.