Is there any way to make a function's return accessible via a property?

后端 未结 4 1214
小鲜肉
小鲜肉 2021-01-27 03:30

I\'m a JS dev, experimenting with functional programming ideas, and I\'m wondering if there\'s anyway to use chains for synchronous functions in the way the promise chains are w

4条回答
  •  逝去的感伤
    2021-01-27 03:45

    It is really a bad idea to modify Function.prototype or Number.prototype because you will pollute the default JavaScript objects, say: what if other framework also do the evil and add their own square?

    The recommended way is to make an object by your self.

    function num(v) {
        this.v = v;
        this.val = function() { return this.v; };
    
        this.square = function() { this.v = this.v * this.v; return this; };
        //and you can add more methods here
        this.sqrt = function() { this.v = Math.sqrt(this.v); return this; };
        return this;
    }
    
    var n = new num(2)
    console.log(n.square().square().sqrt().val());

提交回复
热议问题