BoLe
BoLe

Reputation: 163

Hide object's field in JavaScript

I defined a blueprint for a simple stopwatch object with this function constructor:

function StopWatch() {
    function now() {
        var d = new Date();
        return d.getTime();
    }
    this.start = now();
    this.elapsed = function() {
        return Math.round((now() - this.start) / 1000);
    }
}

I can now save the reference to a new stopwatch in s:

var s = new Stopwatch();

And obtain the time elapsed in seconds:

s.elapsed();

But the start property is also accessible. How can I hide it?

Upvotes: 1

Views: 153

Answers (1)

thefourtheye
thefourtheye

Reputation: 239653

You are including the start property in the object being constructed, by doing

this.start = now();

Instead, you can simply declare the variable locally and it will still be available to the elapsed function, because of the closure property.

function StopWatch() {
    var start = (new Date()).getTime();

    this.elapsed = function() {
        return Math.round(((new Date()).getTime() - start) / 1000);
    }
}

Or, you can return an object from the function, like this

function StopWatch() {
    var start = (new Date()).getTime();

    return {
        elapsed: function() {
            return Math.round(((new Date()).getTime() - start) / 1000);
        }
    }
}

Upvotes: 3

Related Questions