26

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?

Jek
  • 5,546
  • 9
  • 37
  • 67

2 Answers2

37

Functions have 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.

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.

Machavity
  • 30,841
  • 27
  • 92
  • 100
Lpc_dark
  • 2,834
  • 7
  • 32
  • 49
3

It takes the value of this (which is determined by how the function is called) and stores it in a variable (which is still accessible in the closure (that will have a different value of this when it is called) that getConfig is returning).

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335