---
title: "js prototype原型对象用处"
author: "easy0917"
date: "2011-09-02T13:38:04Z"
tags: []
categories: ["Web前端"]
slug: "js-prototype"
draft: false
lastmod: "2011-09-02T13:38:04Z"
id: 1164251
url: "https://easy0917.iteye.com/blog/1164251"
---

```java
function Bird(){
}
var bird = new Bird();
alert(Bird.prototype); // [object object]
alert(bird.prototype); // undefined
```

1、使用prototype实现继承：

```java
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扩张现有的数组的方法。

```java

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
```