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

后端 未结 1 1969
一生所求
一生所求 2021-01-18 08:50

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

_initEvents : functio         


        
相关标签:
1条回答
  • 2021-01-18 09:29

    When you call:

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

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

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

    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).

    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...)
    

    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.

    0 讨论(0)
提交回复
热议问题