IE8 Array.prototype.slice: 'this' is not a JavaScript object

I get this error message only in IE8, and I do not know how to convert an existing function for compatibility with IE8.

_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(); }); }, 

above is just a part of it, I don’t think the rest is necessary. The error is here:

  Array.prototype.slice.call( this.menuItems ) 
+6
source share
1 answer

When you call:

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

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

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

you are calling an inline method with a host object like this. In IE 8 and below (and probably many other older browsers) you cannot do this (there is no specification that says you should, although modern browsers allow you).

A simple solution is to convert the menu items into an array using some method other than calling, or add a pad for Array.prototype.forEach and use the CrazyTrain clause:

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

because in browsers without built-in forEach it will be a native method and works fine. But for reliable code, replace all of this with a simple loop.

+5
source

Source: https://habr.com/ru/post/948438/


All Articles