JavaScript Compositions and Incorporations

Currently, I am delving into the world of compositions in Javascript and would like to confirm if my current approach is correct.

I have been working on some exercises that follow this structure:

    class Animal {
    // constructor() {
    // }
    eat = () => {
        console.log("this creature is eating");
    }
}

const AnimalsWithWings = superclass => class extends superclass {
    constructor(Feathers, ...args) {
        super(...args);
        Object.assign(this, { Feathers });
    }
}

const CanDive = superclass => class extends superclass {
    // constructor( ...args) {
    //     super(...args);
    // }
    dive = () => {
        console.log("Can Dive");
    }
}

class Duck extends AnimalsWithWings(CanDive(Animal)) {
    constructor(eats, ...args) {
        super(...args);
        Object.assign(this, { eats });
    }
}

const duffy = new Duck("watermelon", true);
console.log(duffy);

duffy.dive();
duffy.eat()

As I am still navigating my learning journey, any guidance or pointers would be greatly appreciated.

Answer №1

Did the outcome align with your expectations? If so, then it can be considered a suitable approach, although the definition of "correct" may vary in this context.

From my observation, running the code in the console appears to achieve its intended functionality. However, without a clear understanding of the specific domain being represented, such as breaking down Ducks into fundamental components, I cannot provide further insights on your code.

If you opt for this method, I would recommend utilizing a params object instead of altering the constructor signature directly through AnimalsWithWings. This ensures that the order of additional parameters is not reliant on the sequence in which mixins were applied, thereby avoiding unexpected outcomes. It's best to minimize surprises in coding practices.

const AnimalsWithWings = superclass => class extends superclass {
    // Each instance receives the same `params` object.
    // Properties are assigned based on what is provided in the `params`.
    constructor(params) {
        super(params);
        Object.assign(this, { Feathers: params.Feathers });
    }
}

In addition, I personally suggest naming them WithDiving and WithWings for consistency and clarity, emphasizing their nature as modifiers rather than standalone base classes.

While your implementation results in each Duck inheriting a prototype chain four levels deep, it may not pose a performance issue initially. Should optimization become necessary, consider streamlining the mixin process by flattening the prototypes or creating a utility function.

Furthermore, enabling the use of super.method() within methods raises debate regarding its suitability in a mixin. It introduces implicit dependencies between mixins, potentially leading to unforeseen issues.

There are myriad alternative approaches to implementing mixins:

  • Flattening prototypes using a utility function and constructing a base class from which to extend.
  • Bypassing Classes entirely by directly manipulating prototype objects with Object.create().
  • Constructing a Duck prototype through repeated calls to Object.create() instead of extending base classes iteratively.
  • Utilizing helper Controller Classes to manage additional behaviors instead of integrating them directly into the base.
  • Operating solely with plain objects containing data and passing them to functions that expect specific properties, akin to "duck typing."
  • And many other possible methods that involve adding sets of behaviors to a foundational entity.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring TypeScript integration with Google Adsense featuring a personalized user interface

After following a tutorial on implementing Google AdSense in my Angular App, I successfully integrated it. Here's what I did: In the index.html file: <!-- Global site tag (gtag.js) - Google Analytics --> <script> (function(i,s,o,g,r,a,m ...

What causes the sudden change in value of this array?

I can't seem to figure out what's going on with this question. It might be something silly, but I haven't been able to find any clues. Here is the array in question: const superVillains = [ { value: '1', label: 'Thanos&apo ...

Embed Socket.IO into the head tag of the HTML document

After working with socket.IO and starting off with a chat example, my chat service has become quite complex. The foundation of my code is from the original tutorial where they included <script src="/socket.io/socket.io.js"></script> <scrip ...

Error message encountered while trying to instantiate 'FormData'

My contact form was working perfectly fine until recently when it suddenly stopped allowing me to send messages. I keep encountering this error message every time I try to submit the form: Uncaught TypeError: Failed to construct 'FormData': pa ...

How can I delete an item from an array when I click on a selected element using Material React Select Multiple?

I found this helpful CodeSandBox demonstration that walks through how to implement a multiple material select feature. Here is an array containing all the available options: const permissionsGroupList = [ { name: 'Sellers' }, { name: &a ...

What is the best way to get a string as a return value from an async function that uses the request API

I'm currently working on a project that involves printing the HTML code source as a string using the request API. I've created a function to fetch the data as a string, but when I try to print the output, it returns undefined. I'm struggling ...

Perform a search using indexOf method on JSON.stringify objects

I am attempting to determine whether a specific string exists in the following code: var test1 = '{"packageId":"1","machineId":"1","operationType":"Download"},{"packageId":"2","machineId":"2","operationType":"Download"}'; alert("found: " + test1 ...

Display a Popup at 5PM without the need for a page refresh, updating in real-time

After searching extensively online, I was unable to find a suitable solution for my issue. What I am aiming for is to have a popup appear on my page every day at 5:00 PM without the need to refresh the page. If I happen to access the page before 5:00 PM an ...

No search results found for Mongoose text search query

Despite using Mongoose 5.7.8 for my app, the text search feature is not yielding any results. Below is a schema/model example: import mongoose, { Document, Schema } from 'mongoose'; import { Moment } from 'moment'; import { IUser } fr ...

What is the best way to combine this PHP, Javascript, and HTML document together?

My goal is to upload a CSV file exclusively using an HTML form and then save it in an array using PHP and Javascript. I have individual codes that work perfectly when used as separate files. However, when I attempt to combine them into one file, the Javas ...

Creating an HTML return statement to specifically target and extract a certain string while disregarding additional data

Looking for a solution to trim a long string returned by a webpage, while ensuring essential data is not removed. Counting characters is not feasible due to the varying length of the return. The return format is as follows: GET /New%20Messenger&subti ...

Fancybox operates successfully when I manually include a class, yet fails to function when utilizing jQuery's .addClass() method

Below is a snippet of JS code that I use to add Fancybox classes to all hrefs on a webpage: $(function(){ //declaring target variable var $targetTable = $('.photo-frame a'); //looping through each table and adding the fancybox cla ...

The second attempt at an AJAX call is unsuccessful

I am currently developing a form that displays database results based on two entries: Automarke (brand) and Modell (model). You can view the entries here. The Modell dropdown dynamically changes based on the selected Automarke. Here is the code snippet I ...

Can someone explain why Array.from(classList)[0] is not changing to 'className'?

HTML Design <div class="custom-container color-red"> <h3>Hello, I am a customized container</h3> </div> Javascript Logic let element = document.getElementsByClassName('custom-container')[0]; let clas ...

Omit a specific page from the primary Next.js layout within the application directory

In my project, I have a main layout file located at /app/layout.tsx and separate authentication pages. I want the authentication pages to have their own custom layout defined in the file /app/auth/layout.tsx. The issue I am facing is that the main layout ...

Assistance needed for JavaScript link substitution

As I am wrapping up the web application version of my website, I have encountered a small issue. I need to convert the <script> var a=document.getElementsByTagName("a"); for(var i=0;i<a.length;i++) { a[i].onclick=functio ...

Update the displayed number on the input field as a German-formatted value whenever there is a change in the input, all while maintaining

In German decimal numbers, a decimal comma is used. When formatting, periods are also used for grouping digits. For example, the number 10000.45 would be formatted as 10.000,45. I am looking to create an input field (numeric or text) where users can input ...

The querySelector function is now encountering errors due to a change in the data

Currently, I am utilizing a query selector to retrieve an input when a user selects different buttons. Initially, the buttons had options such as: 8x10 inch 12x16 inch 20x24 inch However, I made changes to the options format like so: 8" x 10" ...

Having difficulties creating an array due to identical id tags causing HTML to break in JavaScript

I've been grappling with this issue all day. Before delving into dynamic solutions, I'd like to create multiple divs with unique id tags or classnames rather than repeating ids. Whichever option proves simpler would be greatly appreciated. Curren ...

Create a unique onblur event listener for every element in a loop in Javascript

https://i.sstatic.net/tRYul.png I have added several items to a column in the database, but I am unsure of how to implement an onblur function for validation for each item within a loop. For example, if the NAME field is empty, I want to display an alert ...