Javascript Dateオブジェクト
1975 ワード
前言
どの言語のDateタイプも自分なりの実現方法があります.JSには引用型Dateタイプが内蔵されています.特徴が多く、記録ができます.
Dateを継承
これを参考にします
どの言語のDateタイプも自分なりの実現方法があります.JSには引用型Dateタイプが内蔵されています.特徴が多く、記録ができます.
Dateを継承
これを参考にします
//
// polyfill
Object.setPrototypeOf = Object.setPrototypeOf ||
function (obj, proto) {
obj.__proto__ = proto;
return obj;
};
/**
* , Date
*/
function MyDate() {
// bind Function.prototype, :object, param1, params2...
var dateInst = new (Function.prototype.bind.apply(Date, [Date].concat(Array.prototype.slice.call(arguments))))();
// , MyDate
// ES6 , [[prototype]] , __proto__
Object.setPrototypeOf(dateInst, MyDate.prototype);
dateInst.abc = 1;
return dateInst;
}
// Date,
Object.setPrototypeOf(MyDate.prototype, Date.prototype);
MyDate.prototype.format = function () { // this,arguments new ,
let y = this.getFullYear(),
mon = this.getMonth() + 1,
d = this.getDate(),
h = this.getHours(),
min = this.getMinutes(),
s = this.getSeconds();
mon = mon > 9 ? mon : '0' + mon;
d = d > 9 ? d : '0' + d;
h = h > 9 ? h : '0' + h;
min = min > 9 ? min : '0' + min;
s = s > 9 ? s : '0' + s;
return y + '-' + mon + '-' + d + ' ' + h + ':' + min + ':' + s;
}
let date = new MyDate(1995, 11, 17, 3, 24, 0);
console.log(date.format()); // 1995-12-17 03:24:00
ES 6はBabel包装の継承を経ない:class MyDate extends Date {
constructor() {
super();
this.abc = 1;
}
getTest() {
return this.getTime();
}
}
let date = new MyDate();
// , 1515638988725
console.log(date.getTest());
ES 6はDateタイプのような方法を継承し、ES 5の黒魔法継承方式と同様に、前者が下の層で実現されるだけで、後者は性能問題を引き起こしやすい.