<!doctype html>
汽车
<br> var Car=function(x,y){<br> this.x=x;<br> this.y=y;<br> };<br> Car.prototype.draw = function( ) {<br> var carHtml='<img src="flowers.jpg">';<br> this.carElement=$(carHtml);<br> this.carElement.css({<br> position:"absolute",<br> left:this.x,<br> top:this.y,<br> width:100,<br> height:100<br> });<br> $("body").append(this.carElement);<br> };</p> <p>Car.prototype.moveRight = function( ) {</p> <pre><code>this.x+=10; this.carElement.css({ left:this.x, top:this.y }); $("body").append(this.carElement); </code></pre> <p>};</p> <p>var tesla=new Car(20,20);</p> <p>tesla.draw();</p> <p>tesla.moveRight(); //执行正确</p> <p>setInterval(tesla.moveRight,50);<br><br> /*<br> 执行错误,请解释出错原因:car.html:30 Uncaught TypeError: Cannot read property 'css' of undefined at Car.moveRight <br> */</p></li> </ol> <p>
setInterval(tesla.moveRight,50);
改为
setInterval(function(){ tesla.moveRight(); },50);
即可
直接把 tesla.moveRight 赋值给 定时器 this指向是window
可能是这样执行的
var fn = tesla.moveRight; fn();
F2看看浏览器报什么错误。