Is there a way to Object.freeze() a JavaScript Date?

后端 未结 5 1717
醉梦人生
醉梦人生 2020-12-09 00:46

According to MDN Object.freeze() documentation:

The Object.freeze() method freezes an object: that is, prevents new prop

5条回答
  •  一个人的身影
    2020-12-09 01:11

    The accepted answer is actually flawed, I'm afraid. You actually can freeze an instance of any object including an instance of Date. In support of @zzzzBov's answer, freezing an object instance does not imply the object's state becomes constant.

    One way to prove that a Date instance is truly frozen is by following the steps below:

    var date = new Date();
    date.x = 4;
    console.log(date.x); // 4
    Object.freeze(date);
    date.x = 20; // this assignment fails silently, freezing has made property x to be non-writable
    date.y = 5; // this also fails silently, freezing ensures you can't add new properties to an object
    console.log(date.x); // 4, unchanged
    console.log(date.y); // undefined
    

    But you can achieve the behaviour I suppose you desire as follows:

    var date = (function() {
        var actualDate = new Date();
    
        return Object.defineProperty({}, "value", {
            get: function() {
                return new Date(actualDate.getTime())
            },
            enumerable: true
        });
    })();
    
    console.log(date.value); // Fri Jan 29 2016 00:01:20 GMT+0100 (CET)
    date.value.setTime(0);
    console.log(date.value); // Fri Jan 29 2016 00:01:20 GMT+0100 (CET)
    date.value = null;       // fails silently
    console.log(date.value); // Fri Jan 29 2016 00:01:20 GMT+0100 (CET)
    

提交回复
热议问题