我试图使构造函数工具栏从编辑器继承属性和方法,但效果不佳:
+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);
错误是:
Uncaught TypeError: function call() { [native code] } is not a constructorEditor @ _editor.js:7window.onload @ _editor.js:19
有什么帮助吗?
答案 0 :(得分:0)
好像你发现了这个问题,但我只是想提供一些代码,你和其他人可以选择使用。这是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);
你可以像这样使用它:
var edtr = new Editor(el);
edtr.element === el; //-> true
edtr.customMethod(); //-> true
答案 1 :(得分:0)
如果您不能使用Object.create(旧的IE版本),请使用浏览器方式:
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();