如何在将值分配给对象成员时执行函数

How to perform a function when value is assigned to an object member?

本文关键字:成员 对象 执行 函数 分配      更新时间:2023-09-26

我有一个对象,约会,与成员,时间:

function appointment(date_string){
    this.time = ???;
}

当我从数据库中获取时间时,它有尾随的零。我想在分配值之前删除它们。例如:

var a = new appointment("01/15/2015");
a.time = "01:33:00.000";
console.log(a.time) // should display 01:33:00, NOT 01:33:00.000

我试过了

function appoinment(date_sting) {    
    this.time = function(){return (this.time).replace(".000","");};
}

但这在场景中不起作用。

从 ES 5.1 (ECMA 262) 开始,您可以将 set 运算符与 Object.defineProperty 一起使用

function appointment() {
    Object.defineProperty(this, 'time', {
        set: function (value) {
            value = value + '';
            this._time = value.replace(".000","");
        },
        get: function () {
            return this._time;
        }
    });
}

更新

我想出了一个更好的版本,不会污染this范围:

function appointment() {
    var time;
    Object.defineProperty(this, 'time', {
        set: function (value) {
            value = value + '';
            time = value.replace(".000","");
        },
        get: function () {
            return time;
        }
    });
}

正则表达式是你最好的朋友。 :)

a.time = "01:33:00.000".replace(/'.0+$/, "");

此外,"01:33:00.000".replace(".000") 不执行任何操作的原因可能是因为您忘记指定替换方法的第二个参数:替换第一个参数的字符串:

a.time = "01:33:00.000".replace(".000", "");

不过,我建议使用正则表达式,因为它解决了尾随零数量不同的问题。 :)

编辑:好的,我明白你现在想要实现的目标;你想要一些在分配时动态解析值的东西。在这种情况下,您需要使用 Object.defineProperty:

var Appointment = function(timeString){
    var _time;
    Object.defineProperty(this, "time", {
        get:    function(){ return _time; },
        set:    function(i){
            _time = (i || "").replace(/'.0+$/, "");
        }
    });
    this.time = timeString;
};
console.log(new Appointment("20/08/2015").time);

公平的警告是,在本机JavaScript对象上使用Object.defineProperty在Internet Explorer 8上不起作用。因此,这种方法归结为您愿意支持哪些浏览器。

如果支持IE8(和/或更早版本)是一个问题,我建议改用老式的get/set函数:

var Appointment = function(timeString){
    var _time;
    this.setTime    =   function(i){
        _time = (i || "").replace(/'.0+$/, "");
    };
    this.getTime    =   function(i){
        return _time;
    };
    this.setTime(timeString);
};
console.log(new Appointment("20/08/2015 1:33:00.000").getTime());