What does "let_self = this" mean in Javascript / Typescript?

In this code snippet , why this.identifier n't this.identifier 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 ?

+8
javascript angular typescript
source share
2 answers

Firstly, you get a vote because it is not a stupid question. Some people on Stackoverflow are wayyyy to be eligible.

Functions have something called a context. Context is the object on which the function is called.

 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 has been defined. Person variable is context

so when you say it. this is the same as saying person.name

Now you can attach the function to something else.

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

it will print hi i am jill when it calls.

understand this first.

Now in the second step.

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

Check this.

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

Now the func function is on its own.

Now that he's called who "this," what the hell are you talking about. This is what the function thinks.

In this way, we can help the function 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 special language decides the meaning of this, however the context is not. the context will be what is assigned to it. It will not change if you do not change it.

so using the word _self, context, $ this or something else when you assign a value 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 your variable 

Now when you call your function and it is looking for _self. he knows exactly what you're talking about.

ps. I'm looking for voices too;)

+14
source share

It takes this value (which is defined as the function is called ) and stores it in a variable (which is still available in closure (it will have a different this value when called) returned by getConfig ).

+2
source share

All Articles