创建一个 d3 风格的链式函数

Creating a d3 style chained function

我知道如何执行 a = x().y().z() 之类的链式函数,但我想制作类似 d3 形状函数的东西,最后有 2 组括号。例如:d = d3.line().curve('somecurve')([[10, 60], [40, 90]]).

我得到的最好的是:

function gc() {
    gen = function (z) {
      console.log(x + y + z)
    }
    gen.setx = function(d) {x = d; return(this)}
    gen.sety = function(d) {y = d; return(this)}

    return gen
}

a = gc().setx(1).sety(2)
b = gc().setx(3).sety(4)

a(5)
b(6)

这导致:

12

13

这显然是错误的,因为第二次调用以某种方式覆盖了第一次调用的 x,y 状态。

如有指点,将不胜感激!

在您的代码中,xygen 是全局变量。因此,如果其中两个函数都在写入它们,它们将被覆盖。每次调用 gc 时,您都需要创建一组单独的变量。例如:

function gc() {
    let x = 0; // <----- added
    let y = 0; // <----- added
    const gen = function (z) {
      console.log(x + y + z)
    }
    gen.setx = function(d) {x = d; return(this)}
    gen.sety = function(d) {y = d; return(this)}

    return gen
}

a = gc().setx(1).sety(2)
b = gc().setx(3).sety(4)

a(5)
b(6)