“未捕获的类型错误:非法调用";在 Chrome 中 [英] "Uncaught TypeError: Illegal invocation" in Chrome

查看:36
本文介绍了“未捕获的类型错误:非法调用";在 Chrome 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 requestAnimationFrame 使用以下代码执行一些本机支持的动画时:

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

直接调用support.animationFrame会给...

未捕获的类型错误:非法调用

Uncaught TypeError: Illegal invocation

在 Chrome 中.为什么?

in Chrome. Why?

推荐答案

在您的代码中,您将本地方法分配给自定义对象的属性.当您调用 support.animationFrame(function () {}) 时,它会在当前对象(即支持)的上下文中执行.为了让原生 requestAnimationFrame 函数正常工作,它必须在 window 的上下文中执行.

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.

所以这里正确的用法是support.animationFrame.call(window, function() {});.

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 

另一种选择是使用 Function.prototype.bind() 是 ES5 标准的一部分,可在所有现代浏览器中使用.

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 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆