当你打印
increment
实例,有一个
toString
转换正在发生。您可以使用它来执行增量:
var Increment = (function(n) {
var f = function() {}; // Only serves as constructor
f.prototype.toString = function() {
n += 1;
return n;
}
return f
}(0));
var increment = new Increment();
console.log('value: ' + increment) // value: 1
console.log('value: ' + increment) // value: 2
console.log('value: ' + increment) // value: 3
注意,这个柜台有点全球化。如果要将计数器分开,并为每个实例从0重新启动,请使用
this
:
var Increment = (function(n) {
var f = function() {
this.n = 0;
};
f.prototype.toString = function() {
this.n += 1;
return this.n;
}
return f
}(0));
var increment = new Increment();
console.log('value: ' + increment) // value: 1
console.log('value: ' + increment) // value: 2
console.log('value: ' + increment) // value: 3
increment = new Increment();
console.log('value: ' + increment) // value: 1
console.log('value: ' + increment) // value: 2
console.log('value: ' + increment) // value: 3