What does “let that = this” mean in Javascript/Typescript?

For example,

let person = {
   name:"bill",
   speak:function(){
      console.log("hi i am "+this.name)
   }
}

Functions has something called a context. A context is the object the function is being called on. if you were to do person.speak(), it will be called on the object that was defined. The variable person is the context. So when you say this. it’s the same as saying person.name. Now you can attach the function to something else.

var newperson = {name:'jill'}
newperson.speak = person.speak;

This will print hi i am jill when it’s called.
GetConfig returns a function, however this function is not attached any object.

let person = {
   name:"bill",
   getSpeakFunction:function(){
      return function(){
         console.log('hi my name is '+this.name)
      }

   }
}

let func = person.getSpeakFunction()

Now the function func is all by himself.
Now when it is called who is "this" who the hell are you talking about. That is what the function is thinking.
So we can help the function out by saying.

let person = {
   name:"bill",
   getSpeakFunction:function(){
      let context = this; //listen hear function this is what i am talking about
      return function(){
         console.log('hi my name is '+context.name)
      }

   }
}

let func = person.getSpeakFunction()

this is special the language decides the value of this, however context is not. context will be whatever is assigned to it. It will not change unless you the programmer changes it.

ref link: https://stackoverflow.com/questions/40976031/what-does-let-self-this-mean-in-javascript-typescript/41000508

Alternative way:

fail: function () {
        console.log("Bad session!");
        // 登录态过期
        this.login()
      }
    fail: () => {
        console.log("Bad session!");
        // 登录态过期
        this.login()
      }

Leave a Reply