0

Does closure apply to object's methods in JS? I am new to JS. In the following code I deduce that objects do not create scope and methods remember their lexical environment, even though they are defined as property on object.

let name = "doe";
function foo() {
    let name = "jane";
    return {
        name: "jonh",
        sayName() {
            console.log(name);
        },
    };
}

foo().sayName(); // jane
kbl
  • 129
  • 5
  • 1
    If you want name to be "jonh" then you should use `this.name` which will refer to the returned object from `foo`. Otherwise you get "jane" because the binding "name" in `sayName` closes over the variable from `foo`'s scope. – Jared Smith Aug 20 '23 at 14:26
  • 1
    I sort of guessed that's the rule, but wasn't quite sure. Thank you for confirming my intuition. – kbl Aug 20 '23 at 14:36

0 Answers0