在JavaScript中隐藏对象的字段

时间:2014-10-15 04:53:25

标签: javascript oop encapsulation

我使用此函数构造函数为一个简单的秒表对象定义了蓝图:

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

我现在可以在s中保存对新秒表的引用:

var s = new Stopwatch();

获取以秒为单位的时间:

s.elapsed();

start属性也可访问。我怎么能隐藏它?

1 个答案:

答案 0 :(得分:3)

通过执行

,您将start属性包含在正在构造的对象中
this.start = now();

相反,您可以简单地在本地声明变量,但由于闭包属性,它仍然可用于elapsed函数。

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

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

或者,你可以从函数中返回一个对象,比如

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

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