我创建了两个变量,it、is,那么为什么这两个变量由一个函数创建,(没有调用new)但是nextIndex互不影响呢?而且函数中的nextIndex变量还不会被销毁,是因为闭包的影响吗?var it = makeIterator(['a', 'b']);
it.next()
var is = makeIterator(['a', 'b', 'c']);
console.log(is.next())// { value: "a", done: false }console.log(it.next())
// { value: "b", done: false }function makeIterator(array) { var nextIndex = 0; return {
next: function() { return nextIndex < array.length ?
{value: array[nextIndex++], done: false} :
{value: undefined, done: true};
}
};
}
1 回答

拉丁的传说
TA贡献1789条经验 获得超8个赞
1.首先 nextIndex互不影响
是因为每个函数都有自己的作用域,即使是一个函数,每次函数传入的参数不一样 每次调用都会产生一个新的作用域 。
2.然后是 nextIndex变量还不会被销毁
我觉得是闭包 的作用,因为后面对象中的函数要用到 包含它的函数中的值 所以包含函数不会被销毁, 比如 it
的值是传回的一个对象,而对象中的 next()
方法要用到 makeIterator
函数中的 nextIndex变量
所以makeIterator
函数不会被销毁。
添加回答
举报
0/150
提交
取消