javascript - 更改每个函数的增量作为变量运行
问题描述
我在这里使用@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]
解决方案
当您打印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
推荐阅读
- tensorflow - 从模型中获取张量时出错:变量 batch_normalization_1_3/moving_mean/biased 已经存在,不允许
- excel - 在 Excel 中,限制单元格范围内的字符总数(如 1000 个)
- puppeteer - 如何找到与 Puppeteer 的 `chromium_revision` 匹配的 Chromium 源代码?
- node.js - 在 express js 中存储会话数据的最佳选择是什么
- git - 有没有一种快速的方法来制作虚拟文件并 git commit 它们来模拟工作?
- postgresql - 为什么“子查询用作表达式”允许返回 SETOF 的东西而不是 TABLE?
- python - Python 3.6 舍入为 0.0
- python - 将生成器转换为列表会覆盖 Python 中的值
- amazon-web-services - 我构建了我的 MVP 的前端。现在,我接下来要做什么?
- php - Wordpress:wpdb 有条件地准备