Could you please explain an interview question about this?

var name = "",
    person = {
      name : "",
      getName : function(){
      return function(){
        return this.name;
      };
      }
    };

console.log(person.getName()()); // 

Why did the final print of "Xiao Ming" instead of "Xiao Hong"?
I don"t quite understand the meaning of the last two parentheses in the sentence person.getName () ().
/ / novice do not spray, thank you

Jun.08,2021

this is a matter of scope. The last () of
is self-execution

.
var name = "",
    person = {
      name : "",
      getName : function(){
        var _this = this;
      return function(){
        return _this.name;
      };
      }
    };

console.log(person.getName()()); //

person.getName () the result is a function:

function(){
    return this.name;
}

person.getName () () is the function that executes the returned function with the content of return this.name . At this point, the scope is global, so this.name is equivalent to window.name , that is, "nickname"

.
var name = "",
    person = {
      name : "",
      age: 20,
      getName : function(){
      return function(){
        return this.name;
      };
      }
    };
  person.getName() // : function(){return this.name;}
  
  // 
  var n = (function(){
    return this.name;
  })()  // windowwindowwindowname"" 
  console.log(n)  // ''
  var a = (function(){
    return this.age;
  })()
  console.log(a)  // undefined
Menu