0
function createPerson() {
    var name = "test1";
    var test = {
        "name": "test2",
        "getName": function() {    
            return name;
        }
    };
    return test;
}

Here when I tried, createPerson().getName() it returns test1 value of outer function instead of object variable value i.e., test2.

Why does this happen?

Ajeet Shah
  • 12,593
  • 7
  • 43
  • 60
  • You need to read up scopes and closures, and get your head around ‘this’. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures – somethinghere May 12 '21 at 00:53
  • Yes, after going through scopes and closures, I'm playing around and came up with this. My question is, when there is variable inside the object itself, why is it referring to variable outside the object? Kindly help. It has to return "test2", instead "test1" right? – Geetika Siri May 12 '21 at 00:57
  • Because every function comes with it’s own ‘this’, unless you use something like an arrow function (don't worry about that yet). If that function is called as a merhod on an object, that object is it’s ‘this’. Does that make sense? – somethinghere May 12 '21 at 01:00
  • 1
    I have not used "this" at all here, the variable in the object function has to refer to it's own variable("test2") before searching in the outer scope(test1). Is not it? – Geetika Siri May 12 '21 at 01:02
  • @GeetikaSiri There is only one *variable* `name` in your code. The other `.name` is an object property, and no, it doesn't become available in the scope of the object methods implicitly. – Bergi May 12 '21 at 01:02
  • Thanks, so when I say closure for function getName(), what variables does it have access to? only the variable in the function createPerson()? and object's variables are not part of the scope? Please correct. – Geetika Siri May 12 '21 at 01:06
  • There are no "object variables", so yes. – Bergi May 12 '21 at 01:17
  • Why object variables are not part of it's function scope? – Geetika Siri May 12 '21 at 01:20

0 Answers0