JavaScriptの日付のプロトタイプ
例
日付オブジェクトにmyNameという月の名前のプロパティを与える新しいdateメソッドを作成します。
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 | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |
構文
Date.prototype.name = value
警告
制御していないオブジェクトのプロトタイプを変更することはお勧めしません。
次のような組み込みのJavaScriptデータ型のプロトタイプを変更しないでください。
- 数字
- 文字列
- 配列
- 日付
- ブール値
- 関数
- オブジェクト
自分のオブジェクトのプロトタイプのみを変更してください。
プロトタイププロパティ
JavaScriptprototype
プロパティを使用すると、オブジェクトに新しいプロパティを追加できます。
例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";