JavaScript 提供多个内建对象,比如 String、Date、Array 等等。对象只是带有属性和方法的特殊数据类型

创建直接的实例

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>

<body>
<script>
//var person=new Object();
//person.firstname="John";
//person.lastname="Doe";
//person.age=50;
//person.eyecolor="blue";
//document.write(person.firstname+" is "+person.age+" years old.");
//以上代码可以用以下代码替换
var person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
document.write(person.firstname+" is "+person.age+" years old again");
</script>
</body>
</html>

使用对象构造器创建实例

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>

<body>
<script>
function person(firstname,lastname,age,eyecolor){
    this.firstname=firstname;
    this.lastnam=lastname;
    this.age=age;
    this.eyecolor=eyecolor;
}
var myFather=new person("John","Doe",50,"blue");
document.write(myFather.firstname+" is "+myFather.age+" years old");
</script>
</body>
</html>

有两种方式可以访问对象属性: .property 或 ["property"]

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>

<body>
<script>
var person={
    firstname:"John",
    lastname:"Doe",
    id:5566
    };
    document.write(person.lastname+"<br>");
    document.write(person["lastname"]+"<br>");
</script>
</body>
</html>

 创建和使用对象的方法

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>

<body>
<p>创建和使用对象方法</p>
<p id="demo"></p>
<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id : 5566,
    fullName : function() 
    {
       return this.firstName + " " + this.lastName;
    }
};
document.getElementById("demo").innerHTML = person.fullName();//对象方法作为一个函数定义存储在对象属性中
//document.getElementById("demo").innerHTML = person.fullName;//对象方法是一个函数定义,并作为一个属性值存储
</script>
</body>
</html>