0

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?

Community
  • 1
  • 1
LocalHorst
  • 1,048
  • 2
  • 11
  • 24
  • 1
    requestAnimationFrame sends HD time as argument. Also inside callback, myObj is pointing to argument and not to variable outside – Rajesh Oct 28 '16 at 07:35
  • The values to arguments are assigned when invoking a function, not when defining it. – Teemu Oct 28 '16 at 07:37

2 Answers2

2

In the function requestAnimationFrame(), you are not passing the myObj global object in the callback, you are actually setting the parameter name as myObj accessible only in the callback function scope, which is of type DOMHighResTimeStamp according to the requestAnimationFrame() documentation.

Rax Weber
  • 3,730
  • 19
  • 30
1

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));
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488