JavaScript's dependency injection functionality is ineffective

I am looking to create a function named createCoffee which will take a function argument called knowHow.

    function createCoffee(knowHow){
var x=new knowHow(coffee,beans,milk,sugar);
knowHow.create();
}

This will allow me to use different knowHow functions for creating the coffee.

Next, I will define a sample knowHow function:

    var x=function oneWay(a,b,c,d){
console.log(a+b+c+d)
};

Then I will pass x to the createCoffee function.

Subsequently, I will initialize variables a=5, b=1, c=2, d=2 and call createCoffee(x).

The expected outcome is the logging of the sum of the variables. Could it be related to variable scope?

Is my example logically correct? How can I specify the variables in the oneWay(...) function?

Answer №1

Here's a more efficient way to declare variables for coffee, beans, milk, and sugar:

let coffee=5, beans=1, milk=2, sugar=2;

Answer №2

Many thanks to all who contributed. I successfully accomplished my goal by approaching it in the following manner:

function coffeeMaker(knowledge,coffee,milk,sugar){
    knowledge.create(coffee,milk,sugar);
}

var x={create: function customizedMethod(a,b,c){
    console.log(a+b+c);
}};

coffeeMaker(x,2,3,4);

My objective was to implement the program with an interface-oriented approach similar to that used in Java.

In Java, you can pass a reference to an interface and have different implementations, which is what I aimed for.

This allows me to modify the 'knowledge' object and connect it to the coffeeMaker function.

Although it may seem redundant in this particular scenario, when dealing with numerous behaviors associated with an object, this method proves to be quite effective. My inspiration for this approach comes from the Strategy design pattern.

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

Effective strategies for minimizing the bundle size of your NextJs application

Recently, I launched my first NextJS app and was surprised to see that the initial bundle size is around 1.5Mb, which seems quite large for me as a beginner in using Nextjs. I have shared an image of the yarn build and also my package.json. All the pages ...

Extracting data from a secured internal website using web scraping and JavaScript notifications

Recently, I have been attempting to extract raw XML data from an internal company website (the URL has been omitted for security reasons). To achieve this, I am currently utilizing selenium and beautifulsoup, but I am open to exploring alternative options. ...

Adjusting the margin to center vertical content dynamically

I have encountered a perplexing situation with my layout. In the design below, you can see both double-lined and single-lined text. I have set a margin for the single-lined texts to align them properly. However, when it comes to double-lined text, I find m ...

Strategies for Ensuring Ember JS Waits for Asynchronous Functions to Respond Prior to Rendering

Currently, I'm tackling a project that came to the company through an outsourced channel. My query concerns the rendering of an image src. In the past, images were served from the filesystem. However, we've now transitioned to using AWS S3 bucke ...

Utilizing PHP configurations in JavaScript with AJAX for JSON implementation

Trying to have a config.inc.php file shared between PHP and JavaScript seems to work, but when using ajax, the "error-function" is always triggered. Is there a way to successfully share the config file with working ajax implementation? This is being utili ...

The function putImageData does not have the capability to render images on the canvas

After breaking down the tileset The tiles still refuse to appear on the <canvas>, although I can see that they are stored in the tileData[] array because it outputs ImageData in the console.log(tileData[1]). $(document).ready(function () { var til ...

ReactJs: Struggling to programmatically set focus on an element with React.createRef()

Looking to detect when a user clicks on an arrow using the keyboard? I stumbled upon the Arrow Keys React react module. To make it work, you need to call the focus method on a specific element. Manually clicking on an element does the trick: https://i.s ...

What steps can I take to resolve the error message "TypeError: url.lastIndexOf is not a function" in three.js?

I am currently experimenting with loading a gLTF file in Three.js r105. After successfully loading the file, I decided to try changing the URL post-loading to see if it was possible. However, this decision led me straight into a problem. Initially, I atte ...

Cancel promise chain after action dispatch (rxjs)

My goal is to achieve the following: this.jobManager .queue( // initiate a job ) .then( // perform additional actions, but stop if `ABORT` action is dispatched before completion ) .finally( // carry out necessary ...

I am seeking to showcase an image in a window, and upon the image being clicked, execute the code in a separate window

I am looking to showcase the image provided below. <img src="http://gfx.myview.com/MyView/skins/livesample/image/livesample.gif" alt="" border="0"><a/> Once the image is clicked, I want it to execute the following code. How can I ensure that ...

Combining rows using a specific column in Javascript

Could this particular question already be in existence, but just hasn't been found yet? Is there a method for consolidating multiple values into one row of a 2D array with x rows and 2 columns based on them sharing the same element in the first column ...

Is there a method to adjust the styling of my <header> once the page hits a specific #anchor point?

Seeking some assistance with a website design challenge I am facing. I am currently working on a one-page portfolio site with four #anchor points that serve as "pages". Each div has a height of 100% to fill the entire browser height. The header, which co ...

Encountering an error message saying "assignment to undeclared variable"

I'm attempting to incorporate a react icon picker from material-ui-icon-picker However, I keep encountering an error stating "assignment to undeclared variable showPickedIcon" edit( { attributes, className, focus, setAttributes, setFocus, setState ...

Excessive alerts being produced within the loop

I am trying to remove a wine from a JSON wine list and I want to display an alert if the wine doesn't exist in the JSON file. However, the alert is popping up for every entry in the list. I am struggling to find a way to use an if statement before pro ...

Guide on converting a timestamp output in Node.js

I ran a query to retrieve TimeStamp data from MYSQL using Node JS, and the output is as follows: MyDate: Thu Apr 28 2016 07:02:45 GMT+0700 (SE Asia Standard Time) Can anyone help me convert it to yyyy-mm-dd hh:mm:ss format? ...

Differences in behavior of constructors when utilizing ES6 shorthand notation

ES6 introduced a new way to initialize objects with functions and properties using shorthand notation. // ES6 shorthand notation const obj1 = { a(b) { console.log("ES6: obj1"); } }; // ES5 var obj2 = { a: function a(b) { con ...

Incorporating a self-invoking anonymous function to enhance Sir Trevor within an AngularJS framework while also making use of

I recently started working with AngularJS and I have an App where I am using the Sir Trevor content editor. I want to add some custom blocks to the editor by extending it, but I am having trouble accessing angular services within my extension code. The ext ...

Show me a list of either only development or production dependencies in npm

When attempting to list only the production dependencies from package.json according to the npm docs, I tried: npm list -depth 0 -prod or npm list -depth 0 -only prod However, npm continues to list both dependencies and devDependencies. Can anyone sugg ...

Strange behavior observed with Nuxt Js asyncData method returning values

Currently, I am engaged in a project using nuxt js/vue js. The project requires me to interact with multiple REST APIs. To accomplish this task, I am utilizing the asyncData() function provided by nuxt js to make the API calls within the page component. i ...

Leveraging the power of ng-describe for comprehensive end-to-end testing using protractor

Recently, I stumbled upon a fantastic ng-describe package that simplifies the process of writing unit tests for AngularJS applications. It eliminates the need to remember and write all the boilerplate code required to load, inject, mock, or spy. Has anyon ...