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.
Since an object is not an array, but can behave like an array you need to borrow
push
from theArray
object.But in this case
this
refers to the array object created with the shorthand[]
. So we need to change this into the scope forobj
usingcall
.Because there is a
length
property defined, push will update this value.An empty object is passed as an element
{}
, but any other will do:You can try this, this solves your problrm i guess.
The code in your post has some typos:
As you suspected in your comment in the code, there is a syntax error, which I marked for you. Remove that semicolon.
And then, when trying the example you wrote
obj.addElem
, but in the above object literal you haveaddEl
.The example should work just fine, if you simply copy-paste it.
Sure it will. Why wouldn't it? An array in JavaScript can contain values of different types. It doesn't need to be homogeneous, so yes, you can insert other things than
{}
.It's the object on which the method is called. So it's
obj
. This is how method invocation works. When you callobj.something()
, thethis
insidesomething
will be theobj
.If you still have some doubts about this example, feel free to drop a comment.