对象是拥有属性和方法
可以使用字符来定义和创建 JavaScript 对象:
var person = {
firstName:"木",
lastName:"生火",
age:150,
eyeColor:"black",
id:”C10094207”
};
键值对写法为 name : value (键与值以冒号分割), 通常称为对象属性
访问对象属性
person. age;
person["age "];
对象方法
方法定义了一个函数,并作为对象的属性
创建对象方法 methodName : function() { code lines }
访问对象方法 objectName.methodName()
举例 object_method.html 文件源码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>msh</title>
</head>
<body>
<p id="person"></p>
<script>
var person = {
firstName: "木",
lastName : "生火",
id : "C10094207",
getFullName : function()
{
return this.firstName + " " + this.lastName+" "+"工号:"+this.id;
}
};
document.getElementById("person").innerHTML = person.getFullName();
</script>
</body>
</html>
可使用函数来构造JavaScript 对象
<script>
function person(firstname,lastname,age,id){
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.id=id;
}
myself=new person("sh","m",1000,"C10094207");
</script>
添加新属性与新方法
<script>
function person(firstname,lastname,age,eyecolor){
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
person.prototype.hight= 170;
Person.prototype.fullName = function() {
return this.firstName + " " + this.lastName
};
var mySelf=new person("m","sh",1000,"blue");
mySelf.fullName(); //msh
</script>