Bru*_*lok 3 javascript inheritance class ecmascript-6
我有示例类:
class Something{
constructor(x, y){
this.x = x;
this.y = y;
}
//...
}
Run Code Online (Sandbox Code Playgroud)
当我将这样继承的类:
class Dog extends Something{
constructor(name){
this.name = name;
}
//...
}
Run Code Online (Sandbox Code Playgroud)
Will Dog的构造函数看起来像这样吗?
constructor(x, y, name){
this.x = x;
this.y = y;
this.name = name;
}
Run Code Online (Sandbox Code Playgroud)
如果没有,是否有可能让它像这样工作^?
构造函数是否在JS ECMAScript 6中继承?
不是,不是.但是如果你根本不提供构造函数,JavaScript引擎提供的默认值有点像继承的构造函数.1(与您的示例无关,您已经提供了构造函数Dog.)
Will Dog的课程会是这样的吗?
不.因为您已经定义了构造函数Dog,JavaScript引擎不会为您做任何事情; 这取决于你定义Dog的构造函数并让它Something通过调用super(this在调用之前你不能使用super).
你的Dog构造函数需要接受x和y/或硬编码它自己(或从它得到的参数派生它们):
接受它们:
class Dog extends Something{
constructor(name, x, y) {
super(x, y);
this.name = name;
}
//...
}
Run Code Online (Sandbox Code Playgroud)
硬编码:
// Accepting them:
class Dog extends Something{
constructor(name) {
super(42, 57);
this.name = name;
}
//...
}
Run Code Online (Sandbox Code Playgroud)
(或者当然,只接受x或y硬编码/导出另一个.)
1如果您根本不提供constructor,JavaScript引擎会为您添加一个.
对于基类,它看起来像这样:
constructor() {
}
Run Code Online (Sandbox Code Playgroud)
对于派生类,它看起来像这样:
constructor(...args) {
super(...args);
}
Run Code Online (Sandbox Code Playgroud)
后一个是我说它有点像继承构造函数的原因,因为与Java或C#等语言不同,默认构造函数不接受任何参数和不带参数的调用super,JavaScript的默认值会传递它接收的所有参数.
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |