<!DOCTYPE html>
<!--JavaScript 对象是拥有属性和方法的数据,它是变量的容器,同时对象也是一个变量,但对象可以包含多个值(多个变量)-->
<html>
<head>
<meta charset = "utf=8">
<title>My JS about Object</title>
</head>
<body>
<!--创建JS对象的方法-->
<p>1.创建JavaScript对象</p>
<p id = "create0"></p>
<script>
<!--创建JS对象方法一-->
var person0 = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"} ;
document.getElementById("create0").innerHTML = person0.firstName + " Now is " + person0.age + " years old." ;
</script>
<p id = "create1"></p>
<script>
<!--创建JS对象方法二-->
var person1 =
{
firstName:"Jane",
lastName:"Vic",
age:25,
eyeColor:"brown"
} ;
document.getElementById("create1").innerHTML = person1.firstName + " Now is " + person1.age + " years old." ;
</script>
<hr>
<!--JS对象方法-->
<p>2.JS对象方法</p>
<p>对象的方法定义了一个函数,并作为对象的属性存储</p>
<p id = "fun1"></p>
<p>如果你要访问 person 对象的 fullName 属性,它将作为一个定义函数的字符串返回</p>
<p id = fun2></p>
<script>
var person2 =
{
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue",
<!--对象方法-->
fullName : function()
{
return this.firstName + " " + this.lastName ;
}
} ;
document.getElementById("fun1").innerHTML = "带括号访问对象方法:" + "Full Name is " + person2.fullName() ;
document.getElementById("fun2").innerHTML = "不带括号访问对象方法:" + person2.fullName;
</script>
<hr>
<!--3.JS对象访问-->
<p>JS对象访问方法</p>
<p id = "get0"></p>
<p id = "get1"></p>
<script>
var person3 =
{
firstName:"Herry",
lastName:"Kik",
age:5,
eyeColor:"blue",
<!--对象方法-->
fullName : function()
{
return this.firstName + " " + this.lastName ;
}
} ;
<!--对象属性访问方法一-->
document.getElementById("get0").innerHTML = person3.firstName;
<!--对象属性访问方法二-->
document.getElementById("get1").innerHTML = person3["firstName"] ;
</script>
<p>对象方法的访问方法同2中所示</p>
<hr>
</body>
</html>
运行结果: