简体   繁体   中英

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

In this code snippet , why is it that this.identifier doesn't work but _self.url works?

  getConfig() {
    let _self = this;
    return function () {
      this.page.url = this.url || window.location.href;
      this.page.identifier = _self.identifier;
      this.page.category_id = this.categoryId;
      this.language = this.lang;
    };
}

So does let _self = this actually do?

Firstly, you get an up vote as this is not a silly question at all. Some people on Stackoverflow are wayyyy to entitled.

Functions has something called a context. A context is the object the function is being called on.

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

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.

understand this first.

Now on to step two.

GetConfig returns a function, however this function is not attached any object.

Check this out.

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.

so using the word _self, context, $this or anything else when you assign the value of this to it. it is 'locked in place' like any other regular variable.

let a = 2;
//this will never change

let _self = this //_self will never change as it's your variable 

Now when you call your function and it looks for _self. it knows exactly what you are talking about.

ps. i am seeking votes as well ;)

它需要的值this (这是由确定的函数是如何被调用的变量),并将其存储(这仍然是在封闭访问(这将有一个不同的值, this ,当它被称为)是getConfig正在恢复) 。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM