Can I create a property on a JavaScript object that would be new at every mention?

In the code below, the output will be the same.

function dateObject() {
    this.date = new Date();
}

var wrapper = {
    dateObj: new dateObject()
};

console.log(wrapper.dateObj.date);

setTimeout(function () {
    console.log(wrapper.dateObj.date);
}, 3000);

I actually stumbled upon this check to make sure that the property value has not changed, but now I'm curious. Is there a way to have a property that is not a function, but rather an evaluation of a function that will be new every time? I ask because you can do it in other languages ​​(think System.DateTimein C #).

+4
source share
1 answer

You can use Object.defineProperty.

Here is an example:

function DateObject(time) {
    this._date = new Date(time);
}

Object.defineProperty(DateObject, "now", {
    get: function () {
        return new DateObject(Date.now());
    }
});

Object.defineProperty(DateObject.prototype, "time", {
    get: function () {
        return this._date.getTime();
    }
});

Then each time you refer to this property, it will be equal to the result of evaluating the function get:

// calls new DateObject(Date.now()), like Date.Now in C#
var d = DateObject.now;
// calls d._date.getTime()
d.time;                 

, now DateObject. . time, , DateObject.

. enumerable configurable Object.defineProperty. .

+8

All Articles