如何在不使用原型的情况下链接函数

mit*_*221 16 javascript function method-chaining

我有一堆有用的功能,这些功能是我一生中收集的.

function one(num){
    return num+1;
}

function two(num){
    return num+2;
}
Run Code Online (Sandbox Code Playgroud)

我可以打电话给他们 two(two(one(5)))

但我更愿意使用 (5).one().two().two()

如何在不使用原型的情况下实现此目的?

我试图看看下划线链是如何工作的,但是他们的代码太强烈而无法理解它

Ber*_*rgi 22

点语法是为对象保留的.所以你可以做点什么

function MyNumber(n) {
    var internal = Number(n);
    this.one = function() {
        internal += 1;
        // here comes the magic that allows chaining:
        return this;
    }
    // this.two analogous
    this.valueOf = function() {
        return internal;
    }
}

new MyNumber(5).one().two().two().valueOf(); // 10
Run Code Online (Sandbox Code Playgroud)

或者您将在本机Number对象/函数的原型上实现这些方法.这样就可以了(5).one()...


小智 6

为了避免toValue像在@ Bergi的解决方案中那样在链的末尾调用,您可以使用附加方法的函数.toValue当尝试将原始类型转换为原始类型时,JS将自动调用.

function MyNumber(n) {
    function x () { }
    x.one = function() { n++; return this; };
    x.valueOf = function() { return n; };
    return x;
}
Run Code Online (Sandbox Code Playgroud)

然后,

MyNumber(5).one().one()
> 7
Run Code Online (Sandbox Code Playgroud)