---
title: "Javascript中创建对象"
author: "RobertLiu0905"
date: "2014-10-27T19:00:10Z"
tags: ["JavaScript"]
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2014-10-27T19:00:10Z"
id: 2148452
url: "https://robertliu0905.iteye.com/blog/2148452"
---

创建直接的实例：
这个例子创建了对象的一个新实例，并向其添加了四个属性：
  var person = new Object();
  person.firstName = "Bill";
  person.lastName = "Gates";
  person.age = "56";
  person.eyeColor = "blue";
或
  var person = {firstName:"John",lastName:"Doe",age:50,eyeColor:"blue"};

使用对象构造器：
本例使用函数来构造对象：
  function person(firstName, lastName, age, eyeColor)
  {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.eyeColor = eyeColor;
  }

创建 JavaScript 对象实例
一旦您有了对象构造器，就可以创建新的对象实例，就像这样：
   var pastBoss=new person("Bill","Gates",56,"blue");
   var boss=new person("Steve","Jobs",48,"green");

把属性添加到 JavaScript 对象
您可以通过为对象赋值，向已有对象添加新属性：
假设 personObj 已存在 - 您可以为其添加这些新属性：firstname、lastname、age 以及 eyecolor：
   person.firstname="Bill";
   person.lastname="Gates";
   person.age=56;
   person.eyecolor="blue";
   x=person.firstname;

把方法添加到 JavaScript 对象
方法只不过是附加在对象上的函数。
在构造器函数内部定义对象的方法：
  function person(firstname,lastname,age,eyecolor)
  {
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;

    this.changeName=changeName;
    function changeName(name)
    {
      this.lastname=name;
    }
  }
changeName() 函数 name 的值赋给 person 的 lastname 属性。


JavaScript 类
JavaScript 是面向对象的语言，但 JavaScript 不使用类。
在 JavaScript 中，不会创建类，也不会通过类来创建对象（就像在其他面向对象的语言中那样）。
JavaScript 基于 prototype，而不是基于类的。