使用回调函数实现对外的接口:
a.js:
const lists = {
names: ['zs', 'ls', 'ww'],
hobbies: ['sing', 'reading'],
work: ['administration'],
each: function (callback) {
const all = [].concat(this.names, this.hobbies, this.work);
for (const item of all) {
callback(item);
}
}
}
b.js中调用lists.each:
lists.each(function (item) {
console.log(item);
});
输出:
b.js中调用lists.each不需要知道里面的具体实现逻辑。
iterator可迭代接口:
const lists = {
names: ['zs', 'ls', 'ww'],
hobbies: ['sing', 'reading'],
work: ['administration'],
[Symbol.iterator]: function () {
const all = [...this.names, ...this.hobbies, ...this.work];
let index = 0;
return {
next() {
return {
value: all[index],
done: index++ >= all.length
};
}
}
}
}
外部调用for...of遍历:
for (const item of lists) {
console.log(item);
}
输出: