phantomCoder
phantomCoder

Reputation: 1587

Javascript object related

I am trying to accomplish something like this.

/* Code start */

  function getCurrentTime()
  {
      var date = new Date(),
      time = date.getTime();

      return time;
   }


var jsObject = {
                 "imageOne":"SomeText"+getCurrentTime(),
                 "imageTwo":"someOtherText"+getCurrentTime()
                }


setInterval(function(){
        console.log(jsObject.imageOne);

        }, 3000);
/* Code end */

Each time the timer is executed I need to execute getCurrentTime() and get the latest time. How do I do it?

Upvotes: -1

Views: 77

Answers (2)

pimvdb
pimvdb

Reputation: 154818

If you need to execute things and get a different result each time, you basically need a function:

"imageOne": function() {
  return "SomeText" + getCurrentTime();
},

and:

console.log(jsObject.imageOne());

If really necessary, you can omit the () with a getter, but using a function is more straight-forward.


Using a getter:

get imageOne() {
  return "SomeText" + getCurrentTime();
},

This way accessing obj.imageOne will evaluate to a different value each time, depending on the current time.

Upvotes: 2

Nemoy
Nemoy

Reputation: 3417

Try this:

var jsObject = {
    "imageOne":"SomeText",
    "imageTwo":"someOtherText",
    getLatestByName : function (name) {
       return this[name] + getCurrentTime();
    }
};


setInterval(function(){
    console.log(jsObject.getLatestByName("imageOne"));
}, 3000);

here is the fiddle : http://jsfiddle.net/R7JQ3/

Upvotes: 1

Related Questions