多物體運動傳入obj問題
for (var i = 0; i < aLi.length; i++) {
? ?aLi[i].timer = null;
? ?aLi[i].onmouseover = function () {
? ? ? ?startMove(ali[i], {width:400, height:200});
? ?}
? ?aLi[i].onmouseout = function () {
? ? ? ?startMove(aLi[i], {width:200, height:100});
? ?}
}
當這樣傳入aLi[i]時,瀏覽器會報錯TypeError: Cannot read property 'timer' of undefined
而當傳入this時,就不會存在這個問題
2016-05-01
this的特點是,誰調用指向誰,所以當你第一個參數傳this的時候,改變自身的屬性,這個無異議;
當你將第一個參數傳遞為aLi[i]時,本意是考慮到變量i代表的是當前aLi的索引值,所以可以指向當前的li元素。但事實并非如此,i這個參數在startMove這個方法中執行的時候是undefined的,所以timer屬性也就沒辦法被正確定義了。
2016-05-01
把startMove(ali[i], {width:400, height:200});中的ali[i]換成this試試
可以參考我的一個例子 ?https://github.com/KaiWang0712/jsExercise.git? ? ?多物體同時運動+鏈式運動.html