javascript - Setting correct this-value in requestAnimationFrame -
i have app-object constructer looks this:
var app = function(loadedsettings) { return { init: function() { this.loop(); }, loop: function() { this.update(); window.requestanimationframe(this.loop); }, update: function() { //loop through settings , call update on every object. }, settings: [ //array of settings objects, update methods. ] }; }
then when do:
var theapp = app(settings); theapp.init();
i get:
uncaught typeerror: object [object global] has no method 'update'
because when requestanimationframe called, this-value inside loop function set window.
does know how call requestanimatinframe 'theapp' object set this-value?
you can create bound function (with fixed this
), , pass requestanimationframe:
var app = function(loadedsettings) { return { init: function() { this.loop(); }, loop: function() { this.update(); window.requestanimationframe(this.loop.bind(this)); }, update: function() { //loop through settings , call update on every object. }, settings: [ //array of settings objects, update methods. ] }; }
i think browser supports requestanimationframe support function.prototype.bind, in case come across 1 doesn't, there polyfills available.
Comments
Post a Comment