Ron Royston Ron Royston - 7 months ago 11
Javascript Question

JavaScript - Property Lifetime and Constructor Method Triggering

I really want to have Date.now() available as a property, not a function call or method. In other words I want clock.now.go to return a unix timestamp. I cannot get it to work. The returned timestamp is stagnant from the original call. Below is the code with console results shown. Is it possible to trigger a new timestamp by calling a property, or is a function call, i.e., '()' required?

//Revealing Module Pattern (Public & Private)
var clock = (function() {

// object to expose as public via return
var pub = {};

//constructor function
function Now() {
this.getNow = function() {
return ( Date.now() );
};
this.go = this.getNow();
}

//private
var now = new Now();
//public
pub.test1 = now;
pub.test1.go; //clock.test1.go returns 1461888755076
pub.test1.getNow(); //clock.test1.getNow() returns 1461888767477 (GOOD)
pub.test2 = now.getNow(); //clock.test2 returns 1461888755076 (STALE)
pub.test3 = now.go; //clock.test3 returns 1461888755076 (STALE)
//Return just the public parts
return pub;
}());

Answer

If you want it to be presented as a property, but actually be a live function call, then you can use a Javacript getter.

//Revealing Module Pattern (Public & Private) 
var clock = (function() {

    // object to expose as public via return
    var pub = {};

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

console.log(clock.now);   // returns live time

Or, it could be condensed to this:

//Revealing Module Pattern (Public & Private) 
var clock = (function() {

    // object to expose as public via return
    var pub = { 
        get now() { 
            return Date.now();
        }
     };
     return pub;
}());

console.log(clock.now);   // returns live time

Or, even just this (without the enclosing module pattern):

var clock = { 
    get now() { 
        return Date.now();
    }
 };

console.log(clock.now);   // returns live time
Comments