Reputation: 1643
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#).
Upvotes: 4
Views: 170
Reputation: 106660
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.
Upvotes: 8