Scope of the object instances

class Person{
    constructor(name = "Tom", age = 20, energy = 100) {
        this.name = name;
        this.age = age;
        this.energy = energy;
    }
    sleep() {
        this.energy += 10;
    }
    doSomethingFun() {
        this.energy -= 10;
    }
}

function intern() {
    var intern1 = new Person('Bob', 21, 110);
    intern1.sleep();
    return intern1;
}

var internObj = intern();
console.log(internObj)
Output : Person {name: 'Bob', age: 21, energy: 120}

where will " intern1 " be created, is it in stack record of " intern " function ?
if it is created in stack record, will it not be destroyed when function execution is done ?

What if you had the following:

function intern() {
  var intern1 = [1, 2, 3, 4, 5];
  return intern1;
}

Do you think the array being returned from the function will be destroyed? I hope not, otherwise we’ll have to use global variables for everything :slightly_smiling_face: Since arrays are objects in JS, this is basically the same as your example. So hopefully that convinces you that your new Person object will still be around after you return it from the function.

As to how this works in memory, that’s one of the nice things about JS, it hides all of that from us so we don’t have to worry about it. Basically, JS is smart enough to know that the object you created is going to be used outside of the function it was created in and so it won’t delete it from memory even though the scope of the function has ended.

will it not be destroyed when function execution is done

It is. After the function has finished executing, its execution context goes away. But as you are returning the instance out of the function, it exists in that outer scope.

It doesn’t even matter if it didn’t because you can’t access the inner scope of the function from outside it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.