JavaScript Date prototype 屬性

定義和用法

prototype 構造函數允許您向 Date() 對象添加新的屬性和方法。

在構造屬性時,所有日期對象都將被賦予屬性及其值,作為默認值。

在構造方法時,所有日期對象都可以使用此方法。

注釋:Date.prototype 不引用單個日期對象,而是引用 Date() 對象本身。

注釋:Prototype 是一個全局對象構造器,適用于所有 JavaScript 對象。

實例

創建一個新的日期方法,為日期對象提供一個名為 myProp 的 month-name 屬性:

Date.prototype.myMet = function() {
  if (this.getMonth() == 0){this.myProp = "January"};
  if (this.getMonth() == 1){this.myProp = "February"};
  if (this.getMonth() == 2){this.myProp = "March"};
  if (this.getMonth() == 3){this.myProp = "April"};
  if (this.getMonth() == 4){this.myProp = "May"};
  if (this.getMonth() == 5){this.myProp = "June"};
  if (this.getMonth() == 6){this.myProp = "July"};
  if (this.getMonth() == 7){this.myProp = "August"};
  if (this.getMonth() == 8){this.myProp = "September"};
  if (this.getMonth() == 9){this.myProp = "October"};
  if (this.getMonth() == 10){this.myProp = "November"};
  if (this.getMonth() == 11){this.myProp = "December"};
};

創建一個 Date 對象,然后調用 myMet 方法:

var d = new Date();
d.myMet();
var monthname = d.myProp;

親自試一試

語法

Date.prototype.name = value

技術細節

JavaScript 版本: ECMAScript 1

瀏覽器支持

屬性 Chrome IE Firefox Safari Opera
prototype 支持 支持 支持 支持 支持

相關頁面

教程:JavaScript 日期

教程:JavaScript 日期格式

教程:JavaScript 對象構造器