Struct Embedding in JavaScript

JavaScript doesn’t have a direct equivalent to Go’s struct embedding, but we can achieve similar functionality using object composition and prototypal inheritance. Here’s how we can translate the concept:

// Base "class"
class Base {
    constructor(num) {
        this.num = num;
    }

    describe() {
        return `base with num=${this.num}`;
    }
}

// Container "class" that composes Base
class Container {
    constructor(num, str) {
        this.base = new Base(num);
        this.str = str;
    }

    // Delegate the describe method to the base object
    describe() {
        return this.base.describe();
    }
}

function main() {
    // Create a new Container instance
    const co = new Container(1, "some name");

    // Access the base's fields through the base property
    console.log(`co={num: ${co.base.num}, str: ${co.str}}`);

    // We can also access the base's num directly if we want
    console.log("also num:", co.base.num);

    // Call the describe method, which is delegated to the base
    console.log("describe:", co.describe());

    // In JavaScript, we don't need to explicitly define interfaces
    // We can just use duck typing
    const describer = co;
    console.log("describer:", describer.describe());
}

main();

To run this program:

$ node struct-embedding.js
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1

In this JavaScript version, we use classes to define our structures. The Base class corresponds to the base struct in the original example, and the Container class corresponds to the container struct.

Instead of embedding, we use composition by creating a base property in the Container class. We then delegate the describe method to this base object.

JavaScript doesn’t have explicit interfaces, so we don’t need to define a describer interface. JavaScript uses duck typing, which means that if an object has a method with the correct name, it can be used where that method is expected.

This example demonstrates how we can achieve similar functionality to struct embedding in JavaScript, even though the language doesn’t have this feature directly. It shows how to compose objects, delegate methods, and work with JavaScript’s prototypal inheritance system.