【问题标题】:Creating a unit conversion method for the number prototype为数字原型创建单位转换方法
【发布时间】:2019-06-10 18:59:09
【问题描述】:

我目前正在尝试创建公制和英制比例的单位转换作为数字原型的方法。这是我的代码:

Number.prototype.UnitConversion = function (units){
    switch (units){
        case "Metric":
            this = this/100;
            return this;
        case "English":
            this = this/12;
            return this;
    }
}
var a = 5;
alert(a.UnitConversion("Metric"))

但是我得到一个左侧无效参数错误。这是为什么呢?

【问题讨论】:

    标签: javascript numbers prototype


    【解决方案1】:

    this 在 JavaScript 中是不可变的,这意味着您无法重新分配它,请参阅:this SO post。但是,您可以简单地返回对其进行的一些计算的值:

    Number.prototype.UnitConversion = function(units) {
        switch (units){
            case "Metric":
                return this/100;
                
            case "English":
                return this/12;
                
            default:
                return;
        }
    }
    var a = 5;
    console.log(a.UnitConversion("Metric"))

    【讨论】:

      【解决方案2】:

      这是因为对 this 的意外分配。也许尝试一个更易读、更干净的解决方案?像这样:

      Number.prototype.UnitConversion = function (units){
          let conversion;
          switch (units){
              case "Metric":
                  conversion = this/100;
                  break;
              case "English":
                  conversion = this/12;
                  break;
              //always add a default case
          }
      
          return conversion;
      }

      【讨论】:

      • 它有效,谢谢。为什么需要默认情况^
      • 因为它是“安全后备”。想象有人出于某种原因将“Facebook”作为单位传递,您的代码不知道如何处理它,因为您只有 2 个案例。除非您定义默认值,否则它将返回 undefined。
      猜你喜欢
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 2010-11-04
      • 2023-04-02
      • 2019-10-03
      相关资源
      最近更新 更多