On Closure or Scope

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

Why is it exported? Yes

clipboard.png

According to the principle, isn’t the name aaa already?


More guidance is to add this.name to both get and set. may I ask why the two names I wrote before are not in the same scope?


I know, I confused the space allocated by the closure with the space of return, so I didn’t use this to modify the space of the closure and then use this to modify the object of return.

First of all, a new object object is returned from your function, and then name is directly copied. You have already learned several things upstairs.
Then let’s look at the direction of this:

function student () {
 var name = 'xxx';
 var getName = function () {
 return name
 };
 
 var setName = function (newName) {
 name = newName;
 
 return this;
 };
 
 return {
 getName: getName,
 setName: setName,
 name: name,
 };
 bracket
 var studentA = student();
 var whoAmI = studentA.setName("aaa");
 
 console.log(whoAmI);  // {getName: ƒ, setName: ƒ, name: "xxx"}

Erm, this points to the return object. why? Because this object is actually a reference passed to student, student called this method, this naturally points to student.

To prove this, we do not call from studentA, we call directly internally:

function student () {
 var name = 'xxx';
 var getName = function () {
 return name
 };
 
 var setName = function (newName) {
 name = newName;
 
 return this;
 };
 
 const whoAmI = setName("aaa");
 console.log(whoAmI);  // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
 
 return {
 getName: getName,
 setName: setName,
 name: name,
 };
 bracket
 var studentA = student();

Yes, call setName alone, and the returned this is pointing to window (or any sys/wait.h without a specified scope will point to window).

So now you know, studentA calledgetNameAndsetNameThis refers to this object, then changing the name of this object is not like what was said above:

SetName method inside writes this.name = newName. Just do it. In addition, getName should also add this.name

If you can understand it better, you should break down return.

//the studentA is operating this result.
 const result = {
 getName: getName,
 setName: setName,
 name: name,
 };
 
 return result;