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>
新建檔案
<html>
<head>
<script type="text/javascript">
var person = {
name: "dongjc",
age: 32,
Introduce: function () { alert("My name is " + this.name + ".I'm " + this.age); }
};
person.Introduce();
</script>
</head>
<body>
</body>
</html>
預覽
Clear
- 課程推薦
- 課件下載
課件暫不提供下載,工作人員正在整理中,後期請多關注該課程~ 















