JavaScript - 'this' inside setTimeout and requestAni
JavaScript - 'this' inside setTimeout and requestAnimationFrame
我的问题与以下内容有关:
在 JavaScript 类中使用 "this" 的 setTimeout()
在 setTimeout 内部和函数内部调用函数
我正在尝试实现一个简单的动画循环。draw 函数是状态对象的成员函数。我在让"this"在setTimeout和requestAnimationFrame中工作时遇到问题。
我有以下代码:
ANIM.State.prototype = {
constructor: ANIM.State,
play: function(){
if(!this.paused){
var that = this;
setTimeout(function(){
requestAnimationFrame(that.play);
that.setFrameNum(that.currentFrame + 1); //draw code is in here
}, 1000 / 24);
}
}
};
但是,当我调用 play() 时,它会运行两次并停止。
有没有更好的方法可以做到这一点?如果可能的话,我真的很想将这个函数保留为类函数,而不是全局函数。
您可以使用
这样的.bind()
解决问题:
requestAnimationFrame(that.play.bind(that));
问题是传递给requestAnimationFrame()
的只是对.play
方法的引用,然后将其作为普通函数调用执行,因此this
里面将是错误的,并且不会指向您的对象。 当将方法作为回调传递时,这是一个常见问题,您希望将其调用为 obj.method()
。
有许多可能的解决方法,但现代浏览器中最简单的方法是使用我上面显示的.bind()
。 这实际上创建了一个小的存根函数,然后调用that.play()
而不仅仅是play()
,以便根据需要使用对象引用,并且该存根函数传递给requestAnimationFrame()
。
你也可以这样做(创建你自己的存根函数),尽管.bind()
对我来说似乎更干净:
requestAnimationFrame(function() {
that.play();
});
相关文章:
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- Moment js and IOS
- Rails 3.2 and Paloma gem
- Backbone, TypeScript, and super
- iframe and JavaScript on different pages
- JSON and jQuery Search
- Flash and External Javascript
- JavaScript - 'this' inside setTimeout and requestAni