隐藏对象's字段

Hide object's field in JavaScript

本文关键字:字段 对象 隐藏      更新时间:2023-09-26

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

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属性也是可访问的。我怎么能把它藏起来?

您通过执行将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);
        }
    }
}