Looking at some custom [Symbol.iterator]
tutorial, I came across this syntax and I don't get what's going on under the hood.
Here's a simplified version. I'm confused about how [obj1.prop2]()
actually works.
const obj1 = {
prop1: "I'm a prop",
};
const obj2 = {
[obj1.prop2]() {
console.log("what am I?");
},
obj2prop: "I'm a property",
obj2meth() {
console.log("I'm a method");
},
};
If I use a for..in
loop, there's no prop2
on obj1
, but I can call obj2[obj1.prop2]();
.
A loop on obj2
gets me an undefined
prop.
for (p in obj2) {
console.log("obj2 props: ", p);
}
// obj2 props: undefined
// obj2 props: obj2prop
// obj2 props: obj2meth
So I'm guessing the engine creates a reference to this method bound to obj2
somehow? I'm assuming it has something to do with the execution context, but I could be way off… I'd love some pointer in the right direction.
Thanks!