日期:2014-05-16  浏览次数:20339 次

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