【发布时间】:2018-12-29 04:41:25
【问题描述】:
假设class Cheddar 继承自一个期望对象作为参数的类;基本组成:
class Brand {
constructor(b) {
this.brand = b;
}
getBrand() {
return this.brand;
}
}
class Cheese {
constructor(brand_obj) {
// do stuff...
}
}
1
class Cheddar extends Cheese {
constructor(b) {
super(new Brand(b)); // <-- HERE, I'm a "one-liner" kinda guy :D
}
}
现在当我实例化时:
let snack = new Cheddar("Cabot Clothbound");
我无法访问 Brand 对象,因为它是作为参数创建的。
所以,我尝试在调用 super 之前创建 Brand 并将其放在对象上,如下所示:
2
class Cheddar extends Cheese {
constructor(b) {
this.brand = new Brand(b);
super(this.brand);
}
}
...导致以下错误:
'this' is not allowed before super()
Grr.. 所以,我可以这样做:
3
class Cheddar extends Cheese {
constructor(b) {
let myBrand = new Brand(b);
super(myBrand);
this.brand = myBrand;
}
getBrand() {
return this.brand.getBrand();
}
}
我现在可以愉快地访问奶酪对象上的方法,如下所示:
let snack = new Cheese("Cabot Clothbound");
console.log(snack.getBrand()); //-> Cabot Clothbound
...但是,它变得一团糟。我想成为一个“单线人”。
无论如何,要访问作为此构造函数的参数创建的对象,或者我可以稍微不同地构造事物以使其更容易吗?我觉得我在这里工作太辛苦了。谢谢,基思:^D
【问题讨论】:
-
为什么不只是
this.brand = myBrand;?目前还不清楚您为什么要在其中使用delete和jQuery.extend。 -
@loganfsmyth:看看错误:
'this' is not allowed before super() -
它需要在
super之后,就像在您的第三个示例中一样,您只是突然在(3)中添加了一堆其他代码,我不知道为什么。 -
真的让我修复。我认为我需要进行深层复制。
-
为什么有
getBrand?
标签: javascript class ecmascript-6 arguments composition