let model = function(sex) { return { sex: sex, wear: function(clothes) { console.log(`the ${sex} model wears ${clothes}`); } } }
let maleModel = model('male'); let femaleModel = model('female');
for (let i = 1; i <= 10; i++) { maleModel.wear(`maleClothes${i}`) } // the male model wears maleClothes1 // the male model wears maleClothes2 // the male model wears maleClothes3 // the male model wears maleClothes4 // the male model wears maleClothes5 // the male model wears maleClothes6 // the male model wears maleClothes7 // the male model wears maleClothes8 // the male model wears maleClothes9 // the male model wears maleClothes10
for (let i = 1; i <= 10; i++) { femaleModel.wear(`femaleClothes${i}`) } // the female model wears femaleClothes1 // the female model wears femaleClothes2 // the female model wears femaleClothes3 // the female model wears femaleClothes4 // the female model wears femaleClothes5 // the female model wears femaleClothes6 // the female model wears femaleClothes7 // the female model wears femaleClothes8 // the female model wears femaleClothes9 // the female model wears femaleClothes10
let models = (function() { let models = []; let count = 0; // 计算已创建的对象数量 return { create: function() { if (models.length === 0) { count++; console.log(`the object has created ${count} objects`); return { wear: function(clothes) { console.log(`the model wears ${clothes}`); }, recover: function() { models.push(this); } } } return models.shift() }, wear: function(clothes) { returnthis.create().wear(clothes); } } })()
for (let i = 1; i <= 4; i++) { let model = models.create(); model.wear(`clothes${i}`); setTimeout(() => { model.recover() }, 500) } // the object has created 1 objects // the model wears clothes1 // the object has created 2 objects // the model wears clothes2 // the object has created 3 objects // the model wears clothes3 // the object has created 4 objects // the model wears clothes4
setTimeout(() => { for (let i = 5; i <= 10; i++) { let model = models.create(); model.wear(`clothes${i}`); } }, 1000)
// the model wears clothes5 // the model wears clothes6 // the model wears clothes7 // the model wears clothes8 // the object has created 5 objects // the model wears clothes9 // the object has created 6 objects // the model wears clothes10