This is a piece of code that I couldn't reason about. These prototype array methods are used on elems object but I can't understand why length is affected by it. There is no array that has been defined whatsoever. Yet each add operation (via gather method) increments the 'length'. How does this object behave like an array ? Where are all these values stored in ? Can someone please shed some light on this ?
const elems = {
length: 0,
add: function(elem) {
Array.prototype.push.call(this, elem);
},
gather: function(id) {
this.add(document.getElementById(id))
},
find: function(callback) {
return Array.prototype.find.call(this, callback);
},
}
elems.gather('first');
console.log(elems.length === 1);
elems.gather('second');
console.log(elems.length === 2);
const found = elems.find((elem) => elem.id === 'second');
console.log(found.id === 'second');
<h1 id='first'>Hello</h1>
<h1 id='second'>Stack!</h1>
lengthproperty is changed becausethisis passed to the.call()method.elemobject where key is the index and value is the html string; try logging theelemobject.