0
const person = {
  name: "JONY SINS",
  age: 25,
  walk() {
    let anotherPerson = {
      right() {
        console.log("right");
      },
      left() {
        console.log("left");
      },
    };
    console.log(this);
  },
};

is it possible to call right() and left() function in this object

  • Does this answer your question? [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Jacob Nov 09 '22 at 22:14
  • No, you can't. They're properties of a `anotherPerson` variable inside the `person.walk()` function, but there's no way to access local variables outside the function. – Barmar Nov 09 '22 at 22:21
  • You could do it if `walk()` ended with `return anotherPerson;` – Barmar Nov 09 '22 at 22:23
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Nov 10 '22 at 14:17

1 Answers1

1

anotherPerson is a local variable inside the walk() method. This variable can only be accessed inside the method. You could call anotherPerson.left() from inside walk(), but you can't call it from outside the method.

If the method returned the variable, you could call walk() and then call left() or right() from the returned value.

const person = {
  name: "JONY SINS",
  age: 25,
  walk() {
    let anotherPerson = {
      right() {
        console.log("right");
      },
      left() {
        console.log("left");
      },
    };
    console.log("walk");
    return anotherPerson;
  },
};

let other = person.walk();
other.left();
other.right();
Barmar
  • 741,623
  • 53
  • 500
  • 612