0

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!

Yann
  • 604
  • 2
  • 7
  • 16
  • `[obj1.prop2]` is a fancy way of naming a method `"undefined"`, since `obj1.prop2` is `undefined`. You could call it as `obj2.undefined()`, `obj2["undefined"]()`, `obj2[undefined]()` or `obj2[obj1.prop2]()` - all the same. – Bergi Feb 14 '21 at 18:40
  • This actually answers my question (I was overthinking things…) whereas linking to something about computed property names doesn't. Thanks Bergi! – Yann Feb 15 '21 at 17:12

0 Answers0