我找到了很多代码来在一个类中创建 getter 和/或 setter,但没有一个是完整的。
我的意图是能够进行比较 (new Time()>myTime
) 等操作
function Time(hours,minutes,seconds,milliseconds){
// ...
return this.format()
}
Time.prototype = {
format: function(format){
return this.replace(...) // return in HH:MM:SS MMM format as default
},
// other methods...
}
最佳答案
如果你想要自定义比较,你可以实现 Object.prototype.valueOf() .在使用 <、>、+ 等运算符时将对象强制转换为原语时使用。
例子
var Time = function (x) {
this.x = x;
};
Time.prototype.valueOf = function () {
console.log("valueOf() called");
return this.x;
}
var a = new Time(1);
var b = new Time(2);
console.log(a > b); // false
console.log(a < b); // true
console.log(a + b); // 3
console.log(a << 10); // 1024
console.log(a / b); // 0.5
关于Javascript 将 getter 设置为类本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27233183/