How to extend the Javascript Date object?

前端 未结 12 2081
失恋的感觉
失恋的感觉 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条回答
  •  时光取名叫无心
    2020-12-08 15:57

    Based on answer by @sstur

    We can use Function.prototype.bind() to construct the Date object dynamically with the passed in arguments.

    See: Mozilla Developer Network: bind() method

    function XDate() {
      var x = new (Function.prototype.bind.apply(Date, [Date].concat(Array.prototype.slice.call(arguments))))
      x.__proto__ = XDate.prototype;
      return x;
    }
    
    XDate.prototype.__proto__ = Date.prototype;
    
    XDate.prototype.foo = function() {
      return 'bar';
    };
    

    Verification:

    var date = new XDate(2015, 5, 18)
    console.log(date instanceof Date) //true
    console.log(date instanceof XDate) //true
    console.log(Object.prototype.toString.call(date)) //[object Date]
    console.log(date.foo()) //bar
    console.log('' + date) // Thu Jun 18 2015 00:00:00 GMT-0500 (CDT)
    

提交回复
热议问题