我有两个非常简单的 Javascript 原型(prototype);然而,当试图确保一个原型(prototype)继承另一个原型(prototype)时,我看到了我不理解的行为。我正在关注 Mozilla 开发者网络的 article on inheritance :
const Model = function (data) {
this.doSomething(data);
};
Model.prototype.doSomething = function (data) {
console.log("something");
};
// Second "inheriting" model
const Word = function (data) {
Model.call(this, data);
};
// Example use:
let word = new Word({ literal: "duck" });
当我的代码执行 Model
原型(prototype)的构造函数时,我收到一个在这种情况下我不明白的错误:
this.doSomething is not a function.
由于这是一个相对简单的继承用例,它让我相信我完全遗漏了一些关于原型(prototype)链的东西。
是否无法从继承原型(prototype)的构造函数调用在继承原型(prototype)上定义的函数?
最佳答案
你只是错过了原型(prototype)链
Word.prototype = Object.create(Model.prototype);
打电话之前
var w = new Word('foo');
const Model = function (data) {
this.doSomething(data);
};
Model.prototype.doSomething = function (data) {
console.log("something");
};
// Second "inheriting" model
const Word = function (data) {
Model.call(this, data);
};
Word.prototype = Object.create(Model.prototype);
var w = new Word('foo');
关于javascript - 继承、原型(prototype)函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48158623/