Javascript JS中的原型继承
我试图使构造函数工具栏从编辑器继承属性和方法,但效果不佳:Javascript JS中的原型继承,javascript,Javascript,我试图使构造函数工具栏从编辑器继承属性和方法,但效果不佳: +function(window, $) { function Editor(editor) { this.editor = editor; this.toolBar = new Toolbar.call(this); } function Toolbar() { console.log(this.editor); } window.onload = function() {
+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
这里有什么帮助吗?看起来您已经找到了问题所在,但我只是想提供一些代码,如果您愿意的话,您(和其他人)可以使用这些代码。这是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
如果无法使用Object.create(旧IE版本),请使用跨浏览器方式:
移除
工具栏之前的新建。调用(this)代码>谢谢@BenjaminGruenbaum!!呃,你真的想让工具栏从编辑器继承吗?还是从工具栏进行编辑?两者似乎都错了。编辑器是一个包含工具栏的东西,所以你应该在这里使用合成,而不是继承。如果你想在类固醇上看到这一点,请查看。他就是最初编写jQuery的那个人。@Bergi-谢谢你的编辑。我仍在摆脱支持旧的不相关浏览器的冲动。@RyanWheale:不仅仅是支持浏览器,还有
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();