【问题标题】:Is it possible to add a method to the prototype of the null value?是否可以在 null 值的原型中添加方法?
【发布时间】:2015-02-03 17:51:19
【问题描述】:

我想我已经知道这个问题的答案,但我正在寻找确认。

我想做的是在一个变量上调用 toString() 并且如果 null 返回一个空字符串。我知道我可以使用 String(null) 将 null 转换为“null”,但如果我想做这样的事情,那看起来太难看了:

var amount = myPossiblyNullVar.toString().toFloat();

甚至更简单

var amount = myPossiblyNullVar.toFloat();

我将 toFloat() 定义为

String.prototype.toFloat = function() {
  var float;
  float = parseFloat(this.cleanNum());
  if (isNaN(float)) {
    return null;
  } else {
    return float;
  }
};

根据我的阅读,在 JavaScript 中扩展 NULL 似乎是不可能的。任何人都可以确认这一点或提供我没有想到的替代方案吗?

【问题讨论】:

  • 是的;这是完全不可能的。
  • var amount = maybeNull || maybeNull.toFloat(); 保护它怎么样? (如果您对变量的每次出现都一致地这样做,那么null 将无声地传播而不会出现错误。)
  • TPC。这是个好建议。我现在处理它的方式看起来像var amount = String(maybeNull).toFloat(); 我只是想要看起来像一个方法调用链的东西。愚蠢,但它困扰我。

标签: javascript null prototype


【解决方案1】:

您不想修改 JavaScript null 原型。

var amount = maybeNull ? maybeNull.toFloat() : null;

如果你有空传播支持(ES7)

 var amount = maybeNull?.toFloat();

如果 MaybeNull 为 null,?. 将返回 null 而不是尝试调用 toFloat()

【讨论】:

    猜你喜欢
    • 2016-09-19
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2021-06-30
    相关资源
    最近更新 更多