【问题标题】:How to access an object instantiated as a parameter?如何访问实例化为参数的对象?
【发布时间】: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;?目前还不清楚您为什么要在其中使用 deletejQuery.extend
  • @loganfsmyth:看看错误:'this' is not allowed before super()
  • 它需要在super 之后,就像在您的第三个示例中一样,您只是突然在(3)中添加了一堆其他代码,我不知道为什么。
  • 真的让我修复。我认为我需要进行深层复制。
  • 为什么有getBrand

标签: javascript class ecmascript-6 arguments composition


【解决方案1】:

您还没有完成Cheese 的构造。如果您想从子类中访问 brand_obj,您的 // do stuff 应该包括保存它。

当您调用super(new Brand(b)) 时,品牌对象将最终出现在超类的构造函数中。但是你在那里什么也没做。如果将品牌保存为超类的属性,则子类可以使用它:

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)

【讨论】:

  • 啊,谢谢……好建议;但就我而言,我无权修改 super 类。这是一个打包的库,我只能扩展。 ://
  • @kmiklas 因此,当您单独使用超类并将let c = new Cheese(brand_Obj) 之类的参数传递给它时,品牌对象是否可以从它创建的实例中以任何方式获得?就像c.brand_obj Cheese 对那个参数做了什么?
  • 我检查了super 类的构造函数。它将参数用于某些东西,但不会将其作为键附加到父对象或原型链上。我也许可以偷偷溜进去……如果我对它很好的话。
  • 是的,这很糟糕@kmiklas。在这种情况下,您可能会遇到Grr.. so case 3。
猜你喜欢
  • 2011-01-03
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多