JS闭包的应用

闭包: 存储子封闭作用域的行为叫做闭包

1.使函数只执行一次

function once(fn) {
	let once = false;
	return function () {
		if(!once) {
			once = true;
			fn.apply(this, arguments)
		}
	}
}

2.制造Iterator

const it = makeIterator(['a', 'b']);

it.next() // { value: "a", done: false }
it.next() // { value: "b", done: false }
it.next() // { value: undefined, done: true }

function makeIterator(array) {
  let nextIndex = 0;
  return {
    next: () => {
      return nextIndex < array.length ?
        {value: array[nextIndex++], done: false} :
        {value: undefined, done: true};
    }
  };
}

你可能感兴趣的:(JavaScript)