重提这个是因为我最近想起了一些关于 JavaScript 的事情。这取决于如何检查 NodeList,但是..
const singleNode = ((nodeList) => (node) => {
const layer = { // define our specific case
0: { value: node, enumerable: true },
length: { value: 1 },
item: {
value(i) {
return this[+i || 0];
},
enumerable: true,
},
};
return Object.create(nodeList, layer); // put our case on top of true NodeList
})(document.createDocumentFragment().childNodes); // scope a true NodeList
现在,如果你这样做了
const list = singleNode(document.body); // for example
list instanceof NodeList; // true
list.constructor === NodeList; // true
and list 具有属性 length 1 和 0 作为您的节点,以及从 NodeList 继承的任何内容。
如果你不能使用Object.create,你可以做同样的事情,除了使用原型nodelist的构造函数并设置this['0'] = node;,this['length'] = 1;并使用new创建。
ES5 版本
var singleNode = (function () {
// make an empty node list to inherit from
var nodelist = document.createDocumentFragment().childNodes;
// return a function to create object formed as desired
return function (node) {
return Object.create(nodelist, {
'0': {value: node, enumerable: true},
'length': {value: 1},
'item': {
"value": function (i) {
return this[+i || 0];
},
enumerable: true
}
}); // return an object pretending to be a NodeList
};
}());