我有一个对象,与一名成员(member)的约会,时间:
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;
}
});
}
<小时/>
更新
我想出了一个更好的版本,不会污染这个
'范围:
function appointment() {
var time;
Object.defineProperty(this, 'time', {
set: function (value) {
value = value + '';
time = value.replace(".000","");
},
get: function () {
return time;
}
});
}
关于javascript - 当值被分配给对象成员时如何执行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27985858/