Questions about closures or scopes

function student () {
    var name = "xxx";
    var getName = function () {
        return name
    }
    var setName = function (newName) {
        name = newName;
    }
    return {
        getName: getName,
        setName: setName,
        name: name
    }
}
var studentA = student();
console.log(studentA.getName())
studentA.setName("aaa");
console.log(studentA.getName())
console.log(studentA.name);

Why is the output

clipboard.png

doesn"t it make sense that the name has become aaa?

< hr >

more instructive is to add this.name to both get and set. May I ask why the two name I wrote before are not in the same scope?

< hr >

I see. I confuse the space allocated by the closure with the space of return, so it is useless that this is a modification to the space of the closure, and then using this is a modification to the object of this return


name is the original type. At that moment, return copied the value of name and returned it. Any changes to name in the future will not affect your return value


.

first of all, what comes back in your function is a new object object, and then the name is a direct copy of what you already know upstairs.
then let's take a look at the direction of this:

 

there are actually two name attributes:

  1. one is a private attribute of the function student .
  2. one is the object returned by executing the student function.
The

getName and setName methods both set the private property name of student .
and the last line outputs the name attribute of the returned object.
because the name attribute is a value type, there is no change in one reference and other variables that reference the object, as does the reference type.

Menu