Propriétés prototype de Date JavaScript

Définition et utilisation

prototype Le constructeur permet d'ajouter de nouvelles propriétés et méthodes à l'objet Date().

Lors de la construction des attributs, tous les objets Date recevront les attributs et leurs valeurs en tant que valeurs par défaut.

Lors de la construction du constructeur, tous les objets Date peuvent utiliser cette méthode.

Remarque :Date.prototype ne fait pas référence à un seul objet Date, mais à l'objet Date() lui-même.

Remarque :Prototype est un constructeur d'objet global, applicable à tous les objets JavaScript.

Exemple

Créez une nouvelle méthode de date, fournissant une propriété month-name nommée pour l'objet date :

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

Créez un objet Date, puis appelez la méthode myMet :

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

Essayez-le vous-même

Syntaxe

Date.prototype.name = value

Détails techniques

Version JavaScript : ECMAScript 1

Support du navigateur

Propriétés Chrome IE Firefox Safari Opera
prototype Support Support Support Support Support

Pages associées

Tutoriel :Date JavaScript

Tutoriel :Format de date JavaScript

Tutoriel :Constructeur d'objet JavaScript