---
title: "JavaScript常用\"类\"构建方式"
author: "godasd"
date: "2011-01-31T10:38:02Z"
tags: ["JavaScript", "prototype"]
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2011-01-31T10:39:57Z"
id: 900081
url: "https://godasd.iteye.com/blog/900081"
---

带有构造函数(原型方式)的"类":

```javascript

function Student(name,gender,age){
  this.name = name;
  this.gender = gender;
  this.age = age;
  this.hobby = new Array();
}

Student.prototype.showHobbies = function(){
  var hobbies = "";
  for(var arg in this.hobby){
    hobbies += (this.hobby[arg] + " ");
  }
  alert(this.name + "'s hobbies are "+hobbies);
  hobbies = null;
}


var stu1 = new Student("Bob","male","24");
var stu2 = new Student("Tina","female","23");

stu1.hobby.push("basketball");
stu1.hobby.push("football");
stu2.hobby.push("music");
stu2.hobby.push("dancing");
stu2.hobby.push("reading");

stu1.showHobbies();
stu2.showHobbies();

```


动态原型:              //与上例类似，只是方法也包含在"类"中，更符合视觉观点

```javascript

function Student(name,gender,age){
  this.name = name;
  this.gender = gender;
  this.age = age;
  this.hobby = new Array();

  if(typeof Student._initalized == "undefined")
  {
    Student.prototype.showHobbies = function(){
    var hobbies = "";
    for(var arg in this.hobby){
      hobbies += (this.hobby[arg] + " ");
    }
    alert(this.name + "'s hobbies are "+hobbies);
    hobbies = null;
    }
  }

  Sutdent._initalized = ture;
}


```