var pObj = document.getElementsByTagName('p');
console.log( [].slice.call(pObj) ); // 返回数组形式[p,p,p]
console.log( pObj.slice() ); // Error
我的疑问:
1.两个slice方法中的this是不是都是指向的pObj?
2.正因为typeof pObj是object类型,所以不具备slice方法,正如第二个中的error。但是它又像数组所以可以采用第一种方法,理解的对吗?
3.如果上述两个我理解都对的话,其实slice方法中的this处理的是类数组,现在理解的对吗?
4.请大神一一指正。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
首先document.getElementsByTagName返回的结果并非array,而是
HTMLCollection,可以通过document.getElementsByTagName('p').__proto__查验因为
HTMLCollection的原型里没有slice方法,所以pObj.slice是undefined。如果给它赋值一个function,那么通过pObj.slice()调用时,this就也会指向pObj(问1)至于23,差不多对,本质是浏览器实现的
Array.prototype.slice,包括数组的其他很多方法,是不局限于接受原生数组的,比如这里的HTMLCollection,比如document.querySelectorAll的NodeList,还有函数里面的arguments等实际上,chrome里面的
Array.prototype.slice其实只看length属性和0,1,..这些属性