[英]JavaScript inheritance with constructors that have parameters
I am new to JavaScript and trying to get my head around inheritance when I have a constructor that takes parameters. 我是JavaScript的新手,当我有一个接受参数的构造函数时,我试图绕过继承。
Suppose I have a base object called Base
: 假设我有一个称为Base
的基础对象:
function Base(param1, param2) {
// Constructor for Base that does something with params
}
I want another object, for example called BaseChild
which inherits from Base and then another object called Child
which inherits from BaseChild
. 我想要另一个对象,例如称为BaseChild
对象,该对象从Base继承,然后另一个对象称为Child
对象,该对象从BaseChild
继承。
How would I go about creating the constructors for BaseChild
and Child
using basic JavaScript (ie no special plug-ins)?. 我该如何使用基本的JavaScript (即没有特殊的插件)为BaseChild
和Child
创建构造函数?
Note: 注意:
I thought you might be able create BaseChild as follows: 我认为您可以按照以下方式创建BaseChild:
var BaseChild = new Base(param1, param2);
But I don't have the values for param1
or param2
in BaseChild
, only in Child
. 但是我在BaseChild
没有param1
或param2
的值,仅在Child
。 I hope this makes sense!. 我希望这是有道理的!。
// define the Base Class
function Base() {
// your awesome code here
}
// define the BaseChild class
function BaseChild() {
// Call the parent constructor
Base.call(this);
}
// define the Child class
function Child() {
// Call the parent constructor
BaseChild.call(this);
}
// inherit Base
BaseChild.prototype = new Base();
// correct the constructor pointer because it points to Base
BaseChild.prototype.constructor = BaseChild;
// inherit BaseChild
Child.prototype = new BaseChild();
// correct the constructor pointer because it points to BaseChild
Child.prototype.constructor = BaseChild;
alternative approach using Object.create 使用Object.create的替代方法
BaseChild.prototype = Object.create(Base.prototype);
Child.prototype = Object.create(BaseChild.prototype);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.