0

Here's a piece of code.

var inner = '1';

var obj = (function () {
    var inner = '2';
    return {
        inner: '3',
        say: function () {
            console.log(inner);
        }
    }
})();

obj.say();

Why is say() printing '2' in the end? Not '1' or '3'? Can anyone explain the inner logic in it? Thank you.

Gary Yuan
  • 33
  • 2
  • 9
  • 1
    inner -> 2, this.inner -> 3 – Anurag Srivastava Apr 19 '20 at 16:20
  • 1
    Why not `1`: Because the second `var inner` shadows the first one, i.e. it exists in a scope "closer" to the place where you use it than the first one. Why not `3`: Because that is not a variable definition, it's just a property of the object that you return. You could access it using `this.inner` instead because writing `obj.say()` basically calls the `say` function with `obj` as its `this`. – CherryDT Apr 19 '20 at 16:20
  • 2
    `inner` has **no relation** to `this.inner` – VLAZ Apr 19 '20 at 16:21
  • Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – VLAZ Apr 19 '20 at 17:18

0 Answers0