当我用requestAnimationFrame下面的代码来做一些本机支持的动画时:
requestAnimationFrame
var support = { animationFrame: window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame }; support.animationFrame(function() {}); //error support.animationFrame.call(window, function() {}); //right
直接致电support.animationFrame会给…
support.animationFrame
未捕获的TypeError:非法调用
在Chrome中。为什么?
在您的代码中,您正在将本机方法分配给自定义对象的属性。当您调用时support.animationFrame(function () {}),它将在当前对象(即支持)的上下文中执行。为了使本机requestAnimationFrame函数正常工作,必须在的上下文中执行它window。
support.animationFrame(function () {})
window
因此,此处的正确用法是 support.animationFrame.call(window, function() {});。
support.animationFrame.call(window, function() {});
警报也会发生相同的情况:
var myObj = { myAlert : alert //copying native alert to an object }; myObj.myAlert('this is an alert'); //is illegal myObj.myAlert.call(window, 'this is an alert'); // executing in context of window
另一个选择是使用Function.prototype.bind(),它是ES5标准的一部分,并且在所有现代浏览器中都可用。
var _raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame; var support = { animationFrame: _raf ? _raf.bind(window) : null };