IE8 Array.prototype.slice:'this'不是JavaScript对象 [英] IE8 Array.prototype.slice: 'this' is not a JavaScript object

查看:765
本文介绍了IE8 Array.prototype.slice:'this'不是JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只在IE8中收到此错误消息,我不知道如何转换现有的IE8兼容性函数。

I'm getting this error message only in IE8, and I don't know how to convert the existing function for IE8 compatibility.


_initEvents : function() {
     var self = this;

     Array.prototype.slice.call(this.menuItems).forEach(function(el, i) {
         var trigger = el.querySelector('a');

         if (self.touch) {
             trigger.addEventListener('touchstart', function(ev) {
                   self._openMenu(this, ev); 
               });
         }
         else {
             trigger.addEventListener('click', function(ev) {
                   self._openMenu(this, ev);
               });  
        }
     });
   window.addEventListener('resize', function(ev) {
         self._resizeHandler();
     });

},


以上是只是它的一部分,我不认为其余的是必要的。错误发生在这里:

the above is just a part of it, I dont think the rest is needed. The error happens here:


 Array.prototype.slice.call( this.menuItems )



推荐答案

致电时:

this.menuItems = this.el.querySelectorAll( '.cbp-hsmenu > li' );

分配给 menuItems 的对象是静态 NodeList ,它是一个主机对象。然后当你这样做:

the object assigned to menuItems is a static NodeList, which is a host object. Then when you do:

Array.prototype.slice.call( this.menuItems )

您正在使用主机对象调用内置方法 this 。在IE 8及更低版本(以及可能还有很多其他旧版浏览器)中,你不能这样做(没有规范说明你应该这样,虽然现代浏览器允许你)。

you are calling a built–in method with a host object as this. In IE 8 and lower (and probably lots of other older browsers), you can't do that (there is no specification that says you should, though modern browsers let you).

简单的解决方案是使用除调用之外的其他方法将 menuItems 转换为数组,或者转换为 Array.prototype.forEach 添加垫片并使用CrazyTrain的建议:

The simple solution is to convert menuItems to an array using some other method than call, or to add a shim for Array.prototype.forEach and use CrazyTrain's suggestion:

Array.prototype.forEach.call(this.menuItems, func...)

因为在没有内置 forEach 的浏览器中,它将是一个本机方法并且工作得很好。但是对于健壮的代码,用简单的for循环替换所有代码。

because in browsers without a built–in forEach, it will be a native method and work just fine. But for robust code, replace all that with a simple for loop.

这篇关于IE8 Array.prototype.slice:'this'不是JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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