JavaScript Date 原型
示例
建立一個新的日期方法,為日期物件新增一個名為 myMonth 的月份名稱屬性。
Date.prototype.myMonth = function()
{
if (this.getMonth()==0) {return "January"};
if (this.getMonth()==1) {return "February"};
if (this.getMonth()==2) {return "March"};
if (this.getMonth()==3) {return "April"};
if (this.getMonth()==4) {return "May"};
if (this.getMonth()==5) {return "June"};
if (this.getMonth()==6) {return "July"};
if (this.getMonth()==7) {return "August"};
if (this.getMonth()==8) {return "September"};
if (this.getMonth()==9) {return "October"};
if (this.getMonth()==10) {return "November"};
if (this.getMonth()==11) {return "December"};
}
建立一個 Date 物件,然後呼叫 myMonth 方法
const d = new Date();
let month = d.myMonth();
自己動手試一試 »
描述
prototype
允許您向日期新增新屬性和方法。
prototype
是所有 JavaScript 物件都可用的屬性。
瀏覽器支援
prototype
是 ECMAScript1 (ES1) 功能。
ES1 (JavaScript 1997) 在所有瀏覽器中都得到完全支援
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 是 |
語法
Date.prototype.名稱 = 值
警告
不建議更改您不控制的物件的原型。
您不應更改內建 JavaScript 資料型別的原型,例如
- 數字
- 字串
- 陣列
- 日期
- 布林值
- 函式
- 物件
僅更改您自己的物件的原型。
原型屬性
JavaScript prototype
屬性允許您向物件新增新屬性
示例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
自己動手試一試 »