简体   繁体   中英

Prototype inheritance in JS

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?

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

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM