user3351652 user3351652 - 1 month ago 4
Javascript Question

Object turns into number when passed as argument

I am quite new to this and just stumbled across this strange thing:

I am using the function

requestAnimationFrame
and have to pass an object as an argument. This Question showed me how to pass an argument to the callback function, however when i pass an object, within the function it turns into a (seemingly random) number:

var myObj = {name : "Sanchez", surname: "Pedro"};

console.log("outside", myObj); // shows me the object
console.log("outside", typeof(myObj)); // object

requestAnimationFrame(function(myObj) {

console.log("inside", myObj); // shows me a random number
console.log("inside", typeof(myObj)); // number
// doSomethingToPedro(myObj)

});


(see jsFiddle)

My Question now is, (A) how can i properly pass my object to the callback, and (B) why does this happen?

Answer

When JavaScript calls your callback it passes DOMHighResTimeStamp time as first argument, and myObj in your example is this argument, that's why it's a number. This is mentioned in the docs:

A parameter specifying a function to call when it's time to update your animation for the next repaint. The callback has one single argument, a DOMHighResTimeStamp, which indicates the current time (the time returned from Performance.now() ) for when requestAnimationFrame starts to fire callbacks.

The way you code is structured, you don't need to pass myObj into callback, since it'll be accessible through closure mechanism anyway:

var myObj = {name : "Sanchez",  surname: "Pedro"};
requestAnimationFrame(function(timestamp) {
    doSomethingToPedro(myObj) // I'm accessible through closure
});

If you still want to have object explicitly passed, you can use bind function to bind parameters:

requestAnimationFrame(function(myObj, timestamp) {
    doSomethingToPedro(myObj) // I'm accessible through bound value
}.bind(null, myObj));
Comments