简体   繁体   中英

Why typeof callback become number?

I have a very strange problem with a callback and requestAnimationFrame . It executes successfully one time, but the second time the callback becomes a Number.

 function TEST () { this.michou = "jean"; } TEST.prototype.talk = function(fn) { window.requestAnimationFrame(this.talk.bind(this)); alert(typeof fn); //type of callback fn(); }; var jean = new TEST(); jean.talk(function() { alert("hello"); }); 

If you try this code, you will see in the alert "function" "hello" and "number" "number". Why is "number" shown for the type of callback ?

When your .talk() function is called in the animation frame, there's no fn value passed (though something is passed; see below). If you change the code you can fix that:

TEST.prototype.talk = function(fn) {
  window.requestAnimationFrame(this.talk.bind(this, fn));
  alert(typeof fn); //type of callback
  fn();
};

If you pass fn as the second parameter when you bind the function to the object reference, the function will be invoked with both the proper this value and the parameter.

The number value that your code sees is the high-resolution time stamp that the browser passes in to the animation frame callback. It'll still pass that if the code is changed as above, but it'll be the second parameter, not the first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM