How to chain functions without using prototype?

前端 未结 4 908
既然无缘
既然无缘 2020-12-08 21:42

I have a bunch of useful functions that I have collected during my whole life.

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

function two(num){
    return num+2;
}         


        
4条回答
  •  北海茫月
    2020-12-08 22:48

    In order to avoid having to call toValue at the end of the chain as in @Bergi's solution, you can use a function with attached methods. JS will call toValue automatically when trying to convert to it a primitive type.

    function MyNumber(n) {
        function x () { }
        x.one = function() { n++; return this; };
        x.valueOf = function() { return n; };
        return x;
    }
    

    Then,

    MyNumber(5).one().one()
    > 7
    

提交回复
热议问题