问题描述
当我使用 requestAnimationFrame
做一些原生支持的动画时,使用下面的代码:
var support = {
animationFrame:window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame
};
support.animationFrame(function(){}); //错误
support.animationFrame.call(window,function(){}); // right
直接调用 support.animationFrame
会给... ...
$ b
在Chrome中。为什么?
在您的代码中,您将自定义方法分配给自定义对象的属性。
当您调用 support.animationFrame(function(){})
时,它会在当前对象(即支持)的上下文中执行。为了使本地的requestAnimationFrame函数正常工作,它必须在窗口
的上下文中执行。
这里的用法是 support.animationFrame.call(window,function(){});
。 还有警报:
var myObj = {
myAlert:alert //将本地警报复制到对象
};
myObj.myAlert('这是一个提醒'); //非法
myObj.myAlert.call(窗口,'这是一个提醒'); //在窗口的上下文中执行
另一个选项是使用,它是ES5标准的一部分,可用于所有现代浏览器。
var _raf = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var support = {
animationFrame:_raf? _raf.bind(window):null
};
When I use requestAnimationFrame
to do some native supported animation with below code:
var support = {
animationFrame: window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame
};
support.animationFrame(function() {}); //error
support.animationFrame.call(window, function() {}); //right
Directly calling the support.animationFrame
will give...
in Chrome. Why?
In your code you are assigning a native method to a property of custom object.When you call support.animationFrame(function () {})
, it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window
.
So the correct usage here is support.animationFrame.call(window, function() {});
.
The same happens with alert too:
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
Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.
var _raf = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var support = {
animationFrame: _raf ? _raf.bind(window) : null
};
这篇关于“未捕获的类型错误:非法调用”在Chrome中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!