JavaScript Date prototype properties

Definition and usage

prototype The constructor allows you to add new properties and methods to the Date() object.

When constructing properties, all date objects will be assigned properties and their values as default values.

All the date objects can use this method in the constructor.

Nota:Date.prototype non si riferisce a un singolo oggetto di data, ma all'oggetto Date() stesso.

Nota:Prototype è un costruttore di oggetto globale, applicabile a tutti gli oggetti JavaScript.

Esempio

Crea un nuovo metodo di data, fornendo un attributo month-name chiamato myProp all'oggetto di data:

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"};
;

Crea un oggetto Date e chiama il metodo myMet:

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

Prova tu stesso

Sintassi

Date.prototype.name = value

Dettagli tecnici

Versione JavaScript: ECMAScript 1

Supporto del browser

Proprietà Chrome IE Firefox Safari Opera
prototype Supporto Supporto Supporto Supporto Supporto

Pagine correlate

Tutorial:Data JavaScript

Tutorial:Formato della data JavaScript

Tutorial:Costruttore di oggetti JavaScript