js prototype原型对象用处

function Bird(){
}
var bird = new Bird();
alert(Bird.prototype); // [object Object]
alert(bird.prototype); // undefined

1、使用prototype实现继承:
function Animal(){
this.color = "red";
}
function Bird(){
this.name="小鸟";
}

var b = new Bird();
alert(b.color); // undefined

Bird.prototype = new Animal();
var b_ = new Bird();
alert(b_.color); // red

2、使用prototype扩展现有系统函数:
在javascript中Array有个push()方法,可以向数组中添加新的元素,数组是有序且可以重复的,有时候需要数组中的元素不重复(如果数组中存放的是对象,对象的比较需要自己实现),这时候可以使用prototype扩张现有的数组的方法。

Array.prototype.pushEx = function(obj){
var a = true;
for (var i = 0; i < this.length; i++) {
if (this[i]== obj) {
this[i] = obj;
a =false;
break;
}
}
if(a){
this.push(obj);
}
return this.length;
}
var test1 = new Array();
test1.pushEx("bb");
test1.pushEx("bb");
test1.pushEx("dd");
alert(test1) //bb,dd
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值