javaScript Boolean prototype详解

2019年08月15日 13:53 | 1833次浏览

定义

prototype 属性向js对象添加属性和方法


语法

object.prototype.name=value


示例

通过prototype属性向对象添加属性

<script type="text/javascript">

function test(name,addr,phone)
{
this.name=name;
this.addr=addr;
this.phone=phone;
}

var me=new test("八级大狂风","深圳市xxx","18989011123");

test.prototype.salary=null;
me.salary="20000";

alert(me.salary);

</script>

运行结果:

20000


示例2

通过prototype属性向对象添加方法

<script type="text/javascript">

Boolean.prototype.myColor=function()
{
    if (this.valueOf()==true)
    {
        this.color="green";
    }
    else
    {
        this.color="red";
    }
}

//创建一个 Boolean 对象, 并添加 myColor 方法:
var a=new Boolean(1);
a.myColor();
var b=a.color;
alert("结果"+b)

</script>

运行结果:

结果green



小说《我是全球混乱的源头》

感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程