Javascript &引用;未捕获类型错误:非法调用“;含铬
当我使用Javascript &引用;未捕获类型错误:非法调用“;含铬,javascript,html,google-chrome,typeerror,Javascript,Html,Google Chrome,Typeerror,当我使用requestAnimationFrame使用以下代码执行一些本机支持的动画时: var support = { animationFrame: window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame ||
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(函数(){})
时,它将在当前对象(即支持)的上下文中执行。要使本机requestAnimationFrame函数正常工作,必须在窗口的上下文中执行该函数
因此这里正确的用法是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
另一个选择是使用ES5标准的一部分,在所有现代浏览器中都可以使用
var _raf = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var support = {
animationFrame: _raf ? _raf.bind(window) : null
};
您还可以使用:
var obj = {
alert: alert.bind(window)
};
obj.alert('I´m an alert!!');
当您执行一个方法(即分配给对象的函数)时,您可以在其中使用此
变量来引用此对象,例如:
var obj={
someProperty:true,
someMethod:function(){
console.log(this.someProperty);
}
};
obj.someMethod();//logs true
从Chrome 33开始,第二次调用也会失败,出现“非法调用”。一旦答案是肯定的,很高兴取消否决票@丹达斯卡莱斯库:我正在使用Chrome33,它对我有效。我刚刚复制粘贴了你的代码,并得到了非法调用错误。您肯定会得到非法调用错误,因为第一个语句myObj.myAlert('这是一个警报')代码>是非法的。正确用法是myObj.myAlert.call(窗口“这是一个警报”)
。请正确阅读答案并试着理解它。如果我不是这里唯一一个被困在尝试以相同方式获取console.log.apply的人,“这”应该是控制台,而不是窗口:这并不能完全回答问题。我认为它应该是一个注释,而不是一个答案。此外,绑定到适当的对象也很重要,例如,在处理history.replaceState时,应该使用:var realReplaceState=history.replaceState.bind(history)代码>@DeeY:谢谢你回答我的问题!对于未来的人来说,localStorage.clear要求你.bind(localStorage)
,而不是.bind(window)
。因此,在好的ol时代,它是让log=console.log
和让create=document.createElement
,现在是让log=console.log.bind(console)
和让create=document.createElement.bind(document)
。好,好。