JavaScript创建对象
JavaScript 提供了一些常用的内置对象(稍后介绍),但是有些情况下我们需要自定义地创建对象,以达到特殊的、丰富的功能。
比如我们创建一个“student”对象,并为其指定几个 属性 和 方法:
student = new Object(); // 创建对象“student”
student.name = "Tom"; // 对象属性 名字
student.age = "19"; // 对象属性 年龄
student.study =function() { // 对象方法 学习
alert("studying");
};
student.eat =function() { // 对象方法 吃
alert("eating");
};此外,你也可以这样创建对象:
var student = {};
student.name = "Tom";
……或者这样:
var student = {
name:"Tom";
age:"19";
……
}但是以上方法在创建多个对象时,会产生大量重复代码,所以我们也可以采用函数的方式新建对象:
function student(name,age) {
this.name = name;
this.age = age;
this.study = function() {
alert("studying");
};
this.eat = function() {
alert("eating");
}
}然后通过 new 创建 student 对象的实例:
var student1 = new student('Tom','19');
var student2 = new student('Jack','20');<!DOCTYPE html>
<html>
<body>
<script>
person={firstname:"Bill",lastname:"gates",age:56,eyecolor:"blue"}
document.write(person.firstname + " is " + person.age + " years old.");
</script>
</body>
</html>

小天
原来是这样定义对象的!
8年前 添加回复 0