JavaScript Boolean 对象参考手册
Boolean 对象
Boolean 对象表示两个值:"true" 或 "false"。
创建 Boolean 对象的语法:
new Boolean(value); //构造函数 Boolean(value); //转换函数
参数
参数 value 由布尔对象存放的值或者要转换成布尔值的值。
返回值
当作为一个构造函数(带有运算符 new)调用时,Boolean() 将把它的参数转换成一个布尔值,并且返回一个包含该值的 Boolean 对象。
如果作为一个函数(不带有运算符 new)调用时,Boolean() 只将把它的参数转换成一个原始的布尔值,并且返回这个值。
注释:如果省略 value 参数,或者设置为 0、-0、null、""、false、undefined 或 NaN,则该对象设置为 false。否则设置为 true(即使 value 参数是字符串 "false")。
constructor定义和用法
constructor 属性返回对创建此对象的 Boolean 函数的引用。
语法
object.constructor
实例
在本例中,我们将展示如何使用 constructor 属性:
<script type="text/javascript"> var test=new Boolean(); if (test.constructor==Array
) { document.write("This is an Array"); } if (test.constructor==Boolean
) { document.write("This is a Boolean"); } if (test.constructor==Date
) { document.write("This is a Date"); } if (test.constructor==String
) { document.write("This is a String"); } </script>
输出:
This is a Boolean
prototype定义和用法
prototype 属性使您有能力向对象添加属性和方法。
语法
object.prototype.name=value
实例
在本例中,我们将展示如何使用 prototype 属性来向对象添加属性:
<script type="text/javascript">
function employee(name,job,born)
{
this.name=name;
this.job=job;
this.born=born;
}
var bill=new employee("Bill Gates","Engineer",1985);
employee.prototype.salary=null;
bill.salary=20000;
document.write(bill.salary);
</script>
输出:
20000
toSource()定义和用法
toSource() 方法返回表示对象源代码的字符串。
语法
object.toSource()
提示和注释
注释:该方法在 Internet Explorer 中无效。
实例
下面的例子向您展示 toSource() 方法的用法:
<script type="text/javascript">
function employee(name,job,born)
{
this.name=name;
this.job=job;
this.born=born;
}
var bill=new employee("Bill Gates","Engineer",1985);
document.write(bill.toSource()
);
</script>
输出:
({name:"Bill Gates", job:"Engineer", born:1985})
toString()定义和用法
toString() 方法可把一个逻辑值转换为字符串,并返回结果。
语法
booleanObject.toString()
返回值
根据原始布尔值或者 booleanObject 对象的值返回字符串 "true" 或 "false"。
抛出
如果调用该方法的对象不是 Boolean,则抛出异常 TypeError。
提示和注释
注释:在 Boolean 对象被用于字符串环境中时,此方法会被自动调用。
实例
在本例中,我们将创建一个 Boolean 对象,并把它转换成字符串:
<script type="text/javascript"> var boo = new Boolean(true) document.write(boo.toString()) </script>
输出:
true
valueOf()定义和用法
valueOf() 方法可返回 Boolean 对象的原始值。
语法
booleanObject.valueOf()
返回值
booleanObject 的原始布尔值。
抛出
如果调用该方法的对象不是 Boolean,则抛出异常 TypeError。
实例
在本例中,我们将创建一个 Boolean 对象,并使用 valueOf() 来取得此对象的原始值:
<script type="text/javascript">
var boo = new Boolean(false)
document.write(boo.valueOf()
)
</script>
输出:
false