ECMAScript学习

闭包

2015-02-01  本文已影响125人  云香水识

这一节写一个坑爹的闭包。

var students = [
    {name: "小明"},
    {name: "小虎"},
    {name: "珊珊"},
    {name: "小慧"},
    {name: "大胖"}
];
var sports = [
    "踢足球",
    "打棒球",
    "踢毽子",
    "跳绳子",
    "拔河"
];
for (var i = 0; i < students.length; i++) {
       var sport = sports[i];
    students[i].play = function(){
        console.log( this.name + sport );
    };
};
for (var j = 0; j < students.length; j++) {
    students[j].play();
};

执行结果 :

小明拔河
小虎拔河
珊珊拔河
小慧拔河
大胖拔河
上一篇下一篇

猜你喜欢

热点阅读