scabell 2019-02-22 12:01 采纳率: 0%
浏览 582
已采纳

setInterval执行错误,请解释出错原因

  1. <!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=&#39;<img src="flowers.jpg">&#39;;<br> this.carElement=$(carHtml);<br> this.carElement.css({<br> position:&quot;absolute&quot;,<br> left:this.x,<br> top:this.y,<br> width:100,<br> height:100<br> });<br> $(&quot;body&quot;).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 }); $(&quot;body&quot;).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 &#39;css&#39; of undefined at Car.moveRight <br> */</p></li> </ol> <p>

  • 写回答

2条回答 默认 最新

  • Print_v 2019-02-22 16:07
    关注
    setInterval(tesla.moveRight,50); 
    

    改为

    setInterval(function(){ tesla.moveRight(); },50); 
    

    即可

    直接把 tesla.moveRight 赋值给 定时器 this指向是window
    可能是这样执行的

    var fn = tesla.moveRight;    fn();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已采纳回答 10月31日