代码之家  ›  专栏  ›  技术社区  ›  dwjohnston

依赖注入:同一函数的rest和默认函数参数?

  •  -1
  • dwjohnston  · 技术社区  · 7 年前

    function a(...numbers) {
       return numbers.map(n => b(n)); 
    }
    
    function b(n) {
       return n+1; 
    }
    

    a 没有打电话 b .

    即。

    function a(...numbers, _b=b) {
       return numbers.map(n => _b(n)); 
    }
    

    我不想把函数参数放在第一位,因为开发人员每次都必须传递函数b,或者传递一个空值或类似的值。

    2 回复  |  直到 7 年前
        1
  •  0
  •   0.sh    7 年前

    rest参数只能作为函数接受的最后一个参数使用,它捕获函数参数中未声明的所有参数。实际上,您可以放弃rest参数并传入一个数组

    function a(numbers, _b = b) {
       return numbers.map(n => _b(n)); 
    }
    
    function b(n) {
       return n+1; 
    }
    
    console.log(a([1,2,3,4], f => f * 1));
    
        2
  •  0
  •   dwjohnston    7 年前

    Function.prototype.bind() (有点)解决了这个问题!

    //The convention we will use here is that developers shouldn't use the 
    // _underscore methods in production. 
    
    export const _a = function(_b, ...numbers) {
     return numbers.map(n => _b(n)); 
    }; 
    
    export const b = function(n) {
      return n+1; 
    }
    
    export const a = _a.bind(null, b); 
    
    console.log(a(1,2,3)) //[2,3,4]

    现在你将如何测试这个?

    import { _a } from "../functions";
    
    describe("_a", () => {
    
        it("_a(1,2,3) calls _b three times.", () => {
            const mockFn = jest.fn();
            const a = _a.bind(null, mockFn);
    
            a(1, 2, 3);
    
            expect(mockFn.mock.calls).toHaveLength(3);
        })
    
    }); 
    

    如果你感兴趣的话-我已经开始 Github repo with a more fleshed out example of this approach here .