0

function MyFunc()
{
     var msg = 'hello';
     this.speak = function() {
         console.log(msg);
     }
}

var obj = new MyFunc();
obj.speak();

The weird thing about the above code is that it works. Yet 'msg' is not part of the object. So how is 'msg' kept in memory. I would more understand if I did:

this.msg = 'hello';
console.log(this.msg);

because then it's a part of the instantiated object. but how are regular variables like 'var msg' getting saved with this object?

edit: this question is not the same as closure because this is a specific use case.

Shai UI
  • 50,568
  • 73
  • 204
  • 309
  • 2
    How exactly is this *not* about closures‽ It is. – deceze Dec 20 '18 at 18:24
  • @deceze I'm reading through that answer and it doesn't help me. it's too broad. – Shai UI Dec 20 '18 at 18:24
  • Imagine JavaScript environments to be stored on the heap. – Felix Kling Dec 20 '18 at 18:26
  • @FelixKling why use 'this' then. – Shai UI Dec 20 '18 at 18:27
  • Look at the section titled **An example of a closure** in the accepted answer - it's an exact copy of your code, just different variable names. – chazsolo Dec 20 '18 at 18:27
  • @chazsolo no it's not. I instantiated with a new keyword. – Shai UI Dec 20 '18 at 18:27
  • 1
    What you’re asking is how a closure works. There are 86 answers to that in the duplicate. One of those will be the right one for you. We don’t know what you want to hear exactly and there’s no use writing an 87th answer. – deceze Dec 20 '18 at 18:27
  • 1
    You mean why the function is assigned to `this.speak`? Because otherwise you couldn't call `obj.speak()`. Not sure I understand the question. Maybe you are confused about how `this` works? `this` and closures don't have anything to do with each other. – Felix Kling Dec 20 '18 at 18:28
  • 1
    `new` is irrelevant here, the closure works the same. – deceze Dec 20 '18 at 18:28
  • Or are you asking why one would use `this.msg = ...` instead of just `var msg`? – Felix Kling Dec 20 '18 at 18:30
  • Or are you asking why one would use `this.msg = ...` instead of just `var msg`? In production code, `speak` would be defined on the function's *prototype* and wouldn't have access to the scope of the constructor function. Also `msg` might need to be accessible on the object itself for whatever reasons. Variables and object properties are obviously two very different things. – Felix Kling Dec 20 '18 at 18:31
  • @FelixKling ok so to get outer scope you need this. but inner scope (inside functions) you don't. but how is it stored? – Shai UI Dec 20 '18 at 18:32
  • 3
    `this` has nothing to do with scope (not in that way anyway). In your example, `this` is an object like any other. Maybe this ASCII art helps: https://stackoverflow.com/a/53863193/218196 – Felix Kling Dec 20 '18 at 18:33
  • @FelixKling good stuff. thank you so much. – Shai UI Dec 20 '18 at 18:34

0 Answers0