Question

The code

var x = {};

x.request = window.requestAnimationFrame;

function step(timestamp) {

    console.log('sth');
}

x.request(step);

It returns:

NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object

It should make x.request working the same as window.requestAnimationFrame. I need it because I want to make something like:

x.request = window.requestAnimationFrame
                ||
            window.webkitRequestAnimationFrame
                ||
            window.mozRequestAnimationFrame;
Was it helpful?

Solution 2

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.)

OTHER TIPS

Try

x.request.call(window, step);

That'll make sure that this is window.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top