JavaScript Dependency Injection

后端 未结 12 1626
天涯浪人
天涯浪人 2020-12-22 16:51

I am new at JavaScript. I wonder how dependency injection is being implemented in JavaScript? I searched the internet but couldn\'t find anything.

12条回答
  •  佛祖请我去吃肉
    2020-12-22 17:29

    I'd say DI is an out-of-the-box feature of JS/ES2015. :-) Of course, it is not full featured IOC containers but looks useful, doesn't it? Check out an example below!

    const one = () => 1;
    const two = ({one}) => one + one;
    const three = ({one, two}) => one + two;
    
    // IOC container
    const decimalNumbers = {
      get one() { return one(this); },
      get two() { return two(this); },
      get three() { return three(this); }
    };
    
    const binaryTwo = ({one}) => one + 9;
    
    // child IOC container
    const binaryNumbers = Object.create(decimalNumbers, {
      two: { get() { return binaryTwo(this); } }
    });
    
    console.log(`${decimalNumbers.three} is ${binaryNumbers.three} in binary`);

    You can wrap dependencies in _.once (see underscore or lodash) to turn them into singletons.

    const rand = function() {
      return (min, max) => min + Math.random() * (max - min) | 0;
    };
    
    const pair = function({rand} = this) {
      return [rand(10, 100), rand(100, 1000)];
    };
    
    // IOC container
    const ioc = Object.create({}, {
      rand: {get: rand},
      pair: {get: _.once(pair)} // singleton
    });
    
    console.log(`${[ioc.pair, ioc.pair === ioc.pair]}`);

提交回复
热议问题