How to extend the Javascript Date object?

前端 未结 12 2082
失恋的感觉
失恋的感觉 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:35

    Based on the answers by @sstur and its improvement by @bucabay:

    Note that __proto__ is being used in those answers, which is deprecated and its use is strongly discouraged, at least according to the MDN docs.

    Fortunately, it is possible to do what is desired without using __proto__ by setting each individual function from Date.prototype in our class, which is simplified by making use of Object.getOwnPropertyNames().

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

    A minor disadvantage of this method is that XDate isn't actually a subclass of Date. The check xdateobj instanceof Date is false. But this shouldn't be a worry as you can anyway use the methods of the Date class.

提交回复
热议问题