简体   繁体   English

将'this'与function.apply一起使用时接受的约定

[英]Accepted conventions when using 'this' with function.apply

I'm trying to implement a primitive type of Polish Notation Calculator and I'm using an object to define each operation. 我正在尝试实现波兰符号计算器的原始类型,并且正在使用一个对象来定义每个操作。

Such that calling 这样的呼唤

new RPNCalculator().calculate([4, 5, '+']);

will produce an answer of 9 or 将产生9的答案或

new RPNCalculator().calculate([4, 5, '+', 3, 5, '+', '*']);

will produce an answer of 72. 将得出72的答案。

The code is here: 代码在这里:

function RPNCalculator(arr) {

    this.calculate = function(arr) {
        var resultArr =[];
        for(var i=0; i < arr.length; i++) {
            if(typeof(arr[i]) == 'number') {
                resultArr.push(arr[i]);
            }
            else {
                var a = resultArr.pop();
                var b = resultArr.pop();
                var c = opers[arr[i]].apply(this, [a, b]);
                resultArr.push(c);
            }
        }
        return resultArr.pop();
    }

    var opers = {
        "+": function(a, b) { return a + b; },
        "-": function(a, b) { return a - b; },
        "*": function(a, b) { return a * b; },
        "/": function(a, b) { return a / b; }
    }
}

The calculations work correctly, but what I would like to know is whether the following line 计算工作正常,但是我想知道的是以下行是否

var c = opers[arr[i]].apply(this, [a, b]);

is the best way to invoke the required function contained inside the opers object based on the symbol at the current index in the array, or is there a better way to do it? 是基于数组当前索引处的符号来调用opers对象中包含的所需函数的最佳方法,还是有更好的方法呢?

You don't really need a reference to this in your code, because the functions aren't working on any class members. 您实际上不需要在代码中this进行引用,因为这些函数不适用于任何类成员。

In this case, you can simply do: 在这种情况下,您可以简单地执行以下操作:

var c = opers[arr[i]](a, b);

Which is a little cleaner. 哪个更清洁。 To be the most readable, however, I recommend this: 为了最易读,我建议这样做:

var operator = opers[arr[i]];
var c = operator(a, b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM