---
title: "JS－－prototype属性     "
author: "dzwfeng"
date: "2007-11-21T17:18:56Z"
tags: ["prototype"]
slug: "js-prototype"
draft: false
lastmod: "2007-11-21T17:18:56Z"
id: 142375
url: "https://dzwfeng.iteye.com/blog/142375"
---

在js中，每个对象都有一个prototype属性：返回对象类型原型的引用。很拗口！习语“依葫芦画瓢”，这里的葫芦就是原型，那么“瓢.prototype” 返回的就是葫芦，或者“瓢.prototype= new 葫芦()”。

prototype的用途：

继承 
有一个对象－－子类：

<span style="color:blue">function 子类() ...{
this.lastname = "Samuel";
}</span>有一个对象－－父类：

<span style="color:blue">function 父类() ...{
this.firstname = "Shen";
}</span>现在子类是有名无姓，父类是有姓无名，如果子类要有名有姓的话，只要说明－－子类的原型是父类－－就可以了，即子类继承自父类：

子类.prototype = new 父类();
至此，子类就不再是有名无姓了。

<span style="color:blue">alert(子类.firstname + " " + 子类.lastname);    //Samuel Shen</span>
 

牵一发而动全身 
既然prototype返回的是原型的引用，那么如果改变原型的话，所有继承自该原型的对象都将受到影响。

    <span style="color:blue">function Point(x,y)
    ...{
        this.x = x;
        this.y = y;
    }
    var p1 = new Point(1,2);
    var p2 = new Point(3,4);
    Point.prototype.z = 0; //动态为Point的原型添加了属性
    alert(p1.z);    //0
    alert(p2.z);    //0</span>