【问题标题】:How to access the value of an object from inside a method of the same object in Javascript?如何从Javascript中同一对象的方法内部访问对象的值?
【发布时间】:2009-11-30 20:37:47
【问题描述】:

我正在尝试使用原型在 Object 对象中添加一个 toBool()“方法”...类似这样:

Object.prototype.toBool = function ()
{
 switch(this.toLowerCase())
 {
  case "true": case "yes": case "1": return true;
  case "false": case "no": case "0": case null: return false;
  default: return Boolean(string);
 }
}

var intAmount = 1;
if(intAmount.toBool()) 

但我在尝试从同一对象方法 this.toLowerCase() 中访问对象的值时遇到问题@

应该怎么做?

【问题讨论】:

    标签: javascript prototype methods oop


    【解决方案1】:

    您的代码不起作用,因为 toLowerCase() 是 String 的方法,而不是 Number 的方法。因此,当您尝试在数字 1 上调用 toLowerCase() 时,它不起作用。一个解决方案就是先将数字转换为字符串:

    Object.prototype.toBool = function ()
    {
     switch(String(this).toLowerCase())
     {
      case "true": case "yes": case "1": return true;
      case "false": case "no": case "0": case null: return false;
      default: return Boolean(string);
     }
    }
    

    【讨论】:

    • 在这种情况下,我需要验证创建的对象是否为字符串,然后将 toLowerCase() 应用于 obj。价值...?
    • 所有对象都有一个toString 方法,我认为你应该在这里使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2021-08-18
    • 2012-09-21
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多