This is a problem of context. Context is the value of this
inside the function.
For example:
var a = {
name: 'object a',
fn: function() {
return name;
}
},
b = {
name: 'object b'
};
b.fn = a.fn;
console.log(b.fn());
Which result will you get? You might think that you'd get 'object a'
, because that's how the function was defined. In fact you will get object b
, because that is how the function is called. You are providing a context for the function call, and that context is the object b
.
You can see the clear parallel with your code!
x.request = window.requestAnimationFrame;
x.request(step);
Now, the context for the call is x
. Clearly requestAnimationFrame
cares about its context and won't work with the wrong one.
You therefore need to provide the right one. There are two ways of doing this. You can set the context at the time you call the function using Function#call
, or you can set the context earlier using Function#bind
:
// with call
x.request.call(window, step); // provide the window object as the context
// with bind
x.request = window.requestAnimationFrame.bind(window);
(Note, though, that not all browsers support bind
, so you will need to provide a shim for those that don't.)