How to extend the Javascript Date object?

前端 未结 12 2084
失恋的感觉
失恋的感觉 2020-12-08 14:50

I\'m trying to subclass/extend the native Date object, without modifying the native object itself.

I\'ve tried this:

    var util = require(\'util\')         


        
12条回答
  •  Happy的楠姐
    2020-12-08 15:40

    var SubDate = function() { 
        var dateInst = new Date(...arguments); // spread arguments object
        /* Object.getPrototypeOf(dateInst) === Date.prototype */
        Object.setPrototypeOf(dateInst, SubDate.prototype);   // redirectionA
        return dateInst; // now instanceof SubDate
    };
    
    Object.setPrototypeOf(SubDate.prototype, Date.prototype); // redirectionB
    
    // do something useful
    Object.defineProperty(SubDate.prototype, 'year', {
        get: function() {return this.getFullYear();},
        set: function(y) {this.setFullYear(y);}
    });
    
    var subDate = new SubDate(); 
    subDate.year;                                 // now
    subDate.year = 2050; subDate.getFullYear();   // 2050
    

    The problem with the Date constructor function is already explained in the other answers. You can read about the Date.call(this, ...arguments) problem on Date | MDN (first Note).

    This solution is a compact workaround which works as intended in all supporting browsers.

提交回复
热议问题