JavaScript 物件原型
所有 JavaScript 物件都從原型繼承屬性和方法。
在上一章中,我們學習瞭如何使用物件建構函式
示例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
自己動手試一試 »
我們還了解到,你不能向現有的物件建構函式新增新屬性
要向建構函式新增新屬性,必須將其新增到建構函式函式中
示例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
自己動手試一試 »
原型繼承
所有 JavaScript 物件都從原型繼承屬性和方法。
Date
物件從Date.prototype
繼承Array
物件從Array.prototype
繼承Person
物件從Person.prototype
繼承
Object.prototype
位於原型繼承鏈的頂端
Date
物件、Array
物件和 Person
物件都從 Object.prototype
繼承。
向物件新增屬性和方法
有時你可能想為給定型別的某個物件新增新屬性(或方法)。
有時你可能想為物件建構函式新增新屬性(或方法)。
使用prototype 屬性
JavaScript 的 prototype
屬性允許你向物件建構函式新增新屬性
示例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
自己動手試一試 »
JavaScript 的 prototype
屬性也允許你向物件建構函式新增新方法
示例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
自己動手試一試 »
只修改你自己的原型。切勿修改標準 JavaScript 物件的原型。