简体   繁体   中英

How to access the value of an object from inside a method of the same object in Javascript?

I'm trying to add a toBool() "method" inside the Object object using prototype... something like this:

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()) 

But I'm having an issue trying to access the value of the object from inside the same object method this.toLowerCase()

How should it be done?

Your code doesn't work because toLowerCase() is a method of String, but not of Number. So, when you try to call toLowerCase() on the number 1, it doesn't work. A solution would be just to convert the number to string first:

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);
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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