JavaScript 物件建構函式
物件建構函式
有時我們需要建立許多相同型別的物件。
要建立物件型別,我們使用 物件建構函式。
將建構函式命名為首字母大寫被認為是良好的實踐。
人員物件型別
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
自己動手 »現在我們可以使用 new Person()
建立許多新的 Person 物件。
示例
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
const mySister = new Person("Anna", "Rally", 18, "green");
const mySelf = new Person("Johnny", "Rally", 22, "green");
自己動手 »
屬性預設值
賦予屬性的值將是建構函式建立的所有物件的預設值
示例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
自己動手試一試 »
向物件新增屬性
向已建立的物件新增屬性很簡單
注意
新屬性將新增到myFather中。不會新增到任何其他Person 物件。
向建構函式新增屬性
你不能向物件建構函式新增新屬性
要新增新屬性,必須將其新增到建構函式原型中
建構函式方法
建構函式也可以有方法
示例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
自己動手試一試 »
向物件新增方法
向已建立的物件新增方法很簡單
注意
新方法將新增到myMother中。不會新增到任何其他Person 物件。
向建構函式新增方法
您不能向物件建構函式新增新方法。
這段程式碼將產生 TypeError
示例
Person.changeName = function (name) {
this.lastName = name;
}
myMother.changeName("Doe");
TypeError: myMother.changeName is not a function
新增新方法必須透過建構函式原型實現
示例
Person.prototype.changeName = function (name) {
this.lastName = name;
}
myMother.changeName("Doe");
自己動手試一試 »
注意
changeName() 函式將 name
的值賦給人員的 lastName
屬性,將 this
替換為 myMother
。
內建 JavaScript 建構函式
JavaScript 為所有原生物件都內建了建構函式
new Object() // 一個新的 Object 物件
new Array() // 一個新的 Array 物件
new Map() // 一個新的 Map 物件
new Set() // 一個新的 Set 物件
new Date() // 一個新的 Date 物件
new RegExp() // 一個新的 RegExp 物件
new Function() // 一個新的 Function 物件
自己動手試一試 »
注意
Math()
物件不在列表中。Math
是一個全域性物件。new
關鍵字不能用於 Math
。
您知道嗎?
使用物件字面量 {}
代替 new Object()
。
使用陣列字面量 []
代替 new Array()
。
使用模式字面量 /()/
代替 new RegExp()
。
使用函式表示式 () {}
代替 new Function()
。
示例
""; // 原始字串
0; // 原始數字
false; // 原始布林值
{}; // 物件物件
[]; // 陣列物件
/()/ // 正則表示式物件
function(){}; // 函式
自己動手試一試 »