Is this the right way to implement chaining in javascript?

喜你入骨 提交于 2019-12-08 03:31:21

问题


After reading up online I wrote this simple code that does addition and multiplication via chaining. But reading the code, it looks like to me, that the method "Result" makes the code less readable and kind of seems redundant. Can someone help me get rid of the Result function?

var Calculator = function () {
    var result = 0;
    this.Add = function (x) {

        result = result + x;

        return this;
    };

     this.Multiply = function (x) {

        result = result * x;

        return this;
    };

    this.Result = function () {
        return result;
    }

};


var total = new Calculator().Add(2).Add(3).Multiply(5);

alert(total.Result());

What I am trying to achieve is

var total = new Calculator().Add(2).Add(3).Multiply(5);

alert(total);

回答1:


You could do some interesting stuff with prototyping:

var Calculator = function(){ /*...*/ }

// Works with alert
Calculator.prototype.toString = function(){
   return this.Result();
}

// Works with operators
Calculator.prototype.valueOf = function(){
   return this.Result();
}

var total = new Calculator().Add(2).Add(3).Multiply(5);
alert(total); // 25
total + 1; // 26

Note that the function alert(...) converts the arguments to strings before being displayed using .toString(). This also applies to any other operation that has strings, such as concatenation (ex. total + ""). Operations with numbers use .valueOf() instead.




回答2:


I think returning .Result() is perfectly fine, since you cannot have the chainable methods return one type and then in the end auto-magically turn into something else.

Even the other suggested answers are using methods to turn your Calculator into a result, they are just implicitly invoked by the runtime (e.g. toString in the alert function).

If you want real chaining of numbers you should extend the Number prototype and not use a calculator (but i know, Monkey-patching is evil).



来源:https://stackoverflow.com/questions/27736241/is-this-the-right-way-to-implement-chaining-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!