假设 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 之前创建品牌并将其放在对象上,如下所示:
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
最佳答案
您还没有完成Cheese
的构造。如果您想从子类访问它,您的//do stuff
应该包括保存 brand_obj
。
当您调用 super(new Brand(b))
时,品牌对象将在父类(super class)的构造函数中结束。但是你在那里没有做任何事情。如果将品牌保存为父类(super class)的属性,它将对子类可用:
class Brand {
constructor(b) {
this.brand = b;
}
getBrand() {
return this.brand;
}
}
class Cheese {
constructor(brand_obj) {
this.brand = brand_obj // <= save this!!
}
}
class Cheddar extends Cheese {
constructor(b) {
super(new Brand(b));
console.log("brand in cheddar constructor", this.brand) //<== now you can use it
}
}
let snack = new Cheddar("Cabot Clothbound");
console.log("Brand on instance: ", snack.brand)
关于javascript - 如何访问实例化为参数的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51449819/