javascript - 函数、对象和生成器
问题描述
我试图通过返回i
调用时的不同值来模拟生成器的工作方式。i
函数 a 有效,但函数 a1每次调用时都会给我相同的值。
为什么 a1 不起作用?
function a () {
let i = 0;
return {
next: function() {
return i++;
}
}
}
let b = a();
console.log(b.next()); //output 0
console.log(b.next()); // output 1
console.log(b.next()); // output 2
function a1 () {
let i = 0;
return {
next: i++
}
}
let b1 = a1();
console.log(b1.next); //output 0
console.log(b1.next); //output 0
console.log(b1.next); //output 0
解决方案
b1.next
is not a function. It's just an object property that holds a static value. i++
was calculated and assigned to the property at the time the object was created.
If you want to make it act like a function, define a getter.
function a1 () {
let i = 0;
return {
get next() { return i++; }
}
}
let b1 = a1();
console.log(b1.next); //output 0
console.log(b1.next); //output 1
console.log(b1.next); //output 2
推荐阅读
- python - 处理 tkinter 框架中的视觉溢出?
- jodatime - 新的 DateTime 更改时间
- ansible - 如何解析日志以区分 Ansible 中的不同故障?
- node.js - 如何确定 Yarn 或 npm 包所需的 Node.js 版本
- javascript - 在 WordPress 中使用自动完成会导致一些错误
- javascript - 如何使用 jaredpalmer/presspack 与 Google 地图集成构建主题?
- android - 为什么 target="_blank" 在三星设备上的 Chrome 中不起作用?
- javascript - 完全使用 JavaScript 替换 html 元素(无库)
- angular - Angular 编译警告:“在 '@angular/core' 中找不到导出 'ɵɵdefineInjectable'
- c# - 方法调用中没有异常 UIImage.LoadFromData(null)