How to access an object instantiated as a parameter?

Assume that class Cheddar inherits from a class which expects an object as a parameter; essentially composition:

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
    }
}

Now when I instantiate:

let snack = new Cheddar("Cabot Clothbound");

I can't access the Brand object, because it was created as an argument.

So, I tried to create the Brand and put it on the object before calling super, like this:

2

class Cheddar extends Cheese {
    constructor(b) {
        this.brand = new Brand(b);
        super(this.brand);
    }
}

...which results in the following error:

'this' is not allowed before super()

Grr.. so, I could do it this way:

3

class Cheddar extends Cheese {
    constructor(b) {
        let myBrand = new Brand(b);
        super(myBrand);
        this.brand = myBrand;
    }
    getBrand() {
        return this.brand.getBrand();
    }
}

And I can now happily access the methods on the cheese object like so:

let snack = new Cheese("Cabot Clothbound");
console.log(snack.getBrand()); //-> Cabot Clothbound

...but, it's getting messy. I want to be a "one-liner guy."

Anyway to access the object created as an argument to this constructor, or can I possibly structure things a bit differently to make this easier? I feel like I'm working too hard here. Thx, Keith :^D

1 answer

  • answered 2018-07-20 20:43 Mark Meyer

    You are not finishing the construction of Cheese. Your // do stuff should include saving the brand_obj if you want to access it from subclasses.

    When you call super(new Brand(b)) the brand object will end up in the super class's constructor. But you aren't doing anything with it there. If save the brand as a property on the super class it will be available to the subclass:

    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)