Cannot reproduce MDN's example («Using an object in an array-like fashion»).
let obj = {
length: 0,
addEl: function (element) {
[].push.call(this, element);
};
};
// Node REPL still expect me to do something, so there's an error. Why?
Could you, guys, explain what's wrong here? Also it seems that I don't get the point with the mechanics here:
// from the example:
obj.addElem({});
obj.addElem({});
console.log(obj.length);
// → 2
What if we call the function with some different agrument, not {}
, will it work? And if it won't, then why we should use {}
exactly? What is the this
context here: addEl
method or the object itself? If the second, why not addEl
function: it's not an array function, so it should have its own this
(and, I guess, I'd use something like objThis = this;
property).
One more related question is here.