0

I'm trying to make the constructor function Toolbar inherit properties and methods from the Editor, but is not working good:

+function(window, $) {


  function Editor(editor) {
    this.editor = editor;

    this.toolBar = new Toolbar.call(this);
  }

  function Toolbar() {
    console.log(this.editor);
  }


  window.onload = function() {
    var el = document.querySelectorAll('.editor')[0];

    if (el) {
      var edtr = new Editor(el);
    }
  };

}(window, jQuery);

The error is:

Uncaught TypeError: function call() { [native code] } is not a constructorEditor @ _editor.js:7window.onload @ _editor.js:19

Any helps, here?

2 Answers2

0

It seems like you have found the problem, but I just wanted to offer up some code you (and others) can use if you so choose. This is some generic code for prototypal inheritance in javascript:

// this will serve as the base class
function Toolbar (el) {
    this.element = el;
}

// define some methods on your base class
Toolbar.prototype.customMethod = function () {
    console.log(this instanceof Editor);
}

// create a new class which inherits from the base class
function Editor () {
    Toolbar.apply(this, arguments);
}
Editor.prototype = Object.create(Toolbar.prototype);

And you can use it like this:

var edtr = new Editor(el);
edtr.element === el; //-> true
edtr.customMethod(); //-> true
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96
  • If you want to see this on steroids, check out [John Resig's simple class inheritance](http://ejohn.org/blog/simple-javascript-inheritance/). He's the same guy who originally wrote jQuery. – Ryan Wheale Jul 02 '15 at 23:31
  • @Bergi - thanks for the edit. I'm still shaking off the urge to support older irrelevant browsers. – Ryan Wheale Jul 02 '15 at 23:46
  • @RyanWheale: It's not just browser support, there are [real reasons not to use `new Toolbar`](http://stackoverflow.com/q/12592913/1048572) – Bergi Jul 02 '15 at 23:55
0

Cross browser way in case you can not use Object.create (old IE versions):

function extend(d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
}

// this will serve as the base class
function Toolbar (el) {
    this.element = el;
}

// define some methods on your base class
Toolbar.prototype.customMethod = function () {
   console.log(this instanceof Editor);
}

// create a new class which inherits from the base class
function Editor () {        
} 

extend(Editor, Toolbar);

new Editor().customMethod(); 
Sagi
  • 8,972
  • 3
  • 33
  • 41