How to chain functions without using prototype?

前端 未结 4 906
既然无缘
既然无缘 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:22

    The dot syntax is reserved for objects. So you can do something like

    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
    

    Or you're going to implement these methods on the prototype of the native Number object/function. That would allow (5).one()...

提交回复
热议问题