简体   繁体   English

JavaScript中的依赖注入不起作用

[英]Dependency injection in JavaScript doesn't work

I want to write a function createCoffee that accepts a function argument called knowHow 我想编写一个函数createCoffee,它接受一个名为knowHow的函数参数

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

This is so that I can have different knowHow for how to create the coffee. 这样我就可以对如何制作咖啡有不同的了解。

Then I write a sample knowHow function 然后我写了一个示例knowHow函数

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

I pass x to createCoffee 我将x传递给createCoffee

Then 然后

a=5;b=1;c=2;d=2;

createCoffee(x);

This should createCoffee according to the specified knowHow. 这应该根据指定的knowHow创建咖啡。

I expected that the result would be logging in the sum of the variables. 我预计结果将记录变量的总和。 Does it have something to do with variable scope. 它是否与变量范围有关。

Is the example logically sound. 该示例在逻辑上是否合理。 How can I specify the variables in the oneWay(...) function 如何在oneWay(...)函数中指定变量

而不是初始化a,b,c,d,这样做:

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

Thanks everyone. 感谢大家。 I solved my objective in the following way .... 我用以下方式解决了我的目标......

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

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

coffeeMaker(x,2,3,4);

I wanted to make it so that I could do the program according to interface thing as is done in Java. 我想做到这一点,以便我可以按照Java中的界面操作来完成程序。

In Java you can pass reference to an interface and you can have different implementations. 在Java中,您可以将引用传递给接口,您可以使用不同的实现。 I wanted to achieve the same thing. 我想达到同样的目的。

In this I can change the knowHow and plug it into the coffeeMaker. 在这里我可以改变knowHow并将其插入coffeeMaker。

It looks redundant in the present case but when there are like 10 behaviors associated with an object then it becomes useful. 在当前情况下它看起来多余,但是当有10个与对象相关联的行为时,它变得有用。 I am drawing on the Strategy design pattern for this. 我正在利用战略设计模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM