tags:

views:

42

answers:

1

I want to create an object property that re-calculates it's value each time it is called.

I took at stab at it:

var Foo = { Bar : (function() { return Date(); })() }

alert(Foo.Bar); // shows time at object literal Foo was init'd
                // but need it to show time when it's called

It it even possible?

+5  A: 

Not possible - JS properties are not "executable" like C# properties are. The best you can do is a normal method.

Aside: from a design standpoint I would actual consider a self-changing property to be pretty poor. The principle of least surprise would be better served by a method anyway.

annakata
I agree... a function such as GetCurrentDate() would be more intuitive. +1
Cerebrus
That was a contrived example but I also agree. In my scenario I really would like properties but I'll omit the details here for brevity.
aleemb