2009-11-30 76 views
0

我试图使用原型添加的对象物体内部的toBool()“方法” ......这样的事情:如何从Javascript中的同一对象的方法内访问对象的值?

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

应该怎么做?

回答

1

您的代码不起作用,因为toLowerCase()是String的方法,但不是Number的方法。因此,当您尝试呼叫号码1上的LowCase()时,它不起作用。解决方案只是将数字转换为字符串:

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

在这种情况下,我需要验证创建的对象是否为字符串,然后将toLowerCase()应用于obj。值...? – Juanra 2009-11-30 20:43:55

+0

所有对象都有'toString'方法,我想你应该在这里使用它。用'this.toString()'应该可以工作...' – 2009-11-30 20:53:21

+0

'用'String(this)'工作... ... – Juanra 2009-11-30 21:07:43