闭包

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

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();
};

执行结果 :

小明拔河
小虎拔河
珊珊拔河
小慧拔河
大胖拔河

你可能感兴趣的:(闭包)