Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a property on a JavaScript object that's new every time it's referenced?

Tags:

javascript

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 across this checking to make sure that the value of the property doesn't change, but now I'm curious. Is there a way to have a property that isn't a function, but rather the evaluation of a function, that will be new every time? I ask because you can do it in other languages (think System.DateTime in C#).

like image 664
moarboilerplate Avatar asked Feb 11 '23 11:02

moarboilerplate


1 Answers

You can use Object.defineProperty.

Here's 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 reference this property it will equal the result of the function evaluation of get:

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

As you can see, now is defined on DateObject. This acts like a static property. Then time is defined on the object's prototype which means it will be a property for instances of DateObject.

Note: Research the enumerable and configurable properties for the third argument of Object.defineProperty. They can be useful.

like image 65
David Sherret Avatar answered Feb 13 '23 03:02

David Sherret