首页 > 解决方案 > 更改每个函数的增量作为变量运行

问题描述

我在这里使用@Xotic750 找到了简单解决方案closure

但是,是否可以在没有圆括号的情况下运行函数? 例如

var increment = new Increment()

console.log('value: ' + increment) // value: 1
console.log('value: ' + increment) // value: 2
console.log('value: ' + increment) // value: 3

每个函数运行我都得到了函数[object Object]console.log不是value

    var Increment = (function(n) {
      return function() {
        n += 1;
        return n;
      }
    }(0)); 

    var increment = new Increment();

    console.log('value: ' + increment) // value: [object Object]
    console.log('value: ' + increment) // value: [object Object]
    console.log('value: ' + increment) // value: [object Object]

标签: javascriptfunctionvariablesclosures

解决方案


当您打印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


推荐阅读