首页 > 解决方案 > 函数、对象和生成器

问题描述

我试图通过返回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

标签: javascriptfunction

解决方案


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


推荐阅读