1

I've seen things like this:

function fnx(){
 ctrl = this;
 this.thisedVar = "thisedVar from fnx"
}

I'm trying to figure out what is it useful for. if that function is executed and then this is compared to ctrl, they are the same:

fnx();
console.log(this === ctrl) // true

That's why I don't understand what is the purpose of assigning this to a variable.

Can anyone explain it, please? Thanks.

Julio Rodríguez
  • 447
  • 1
  • 8
  • 23
  • 1
    So that the *this* you want is accessible from another scope. E.g. inside of a callback – GetSet Jan 29 '20 at 14:03
  • Could you please provide a small example? I'd really appreciate it. – Julio Rodríguez Jan 29 '20 at 14:05
  • Have a look at where `ctrl` is declared and in what other locations it is used. If you don't show us the complete code, we can't tell you what it is used for. – Bergi Jan 29 '20 at 14:06
  • If you declared another function inside of `function fnx() { ... }`, and inside that nested function wanted to refer to `fnx`, you could not. By storing a reference to `fnx` as a variable, you can now access it from anywhere within. – Tyler Roper Jan 29 '20 at 14:08
  • Why would you set a variable to another variable. To hold a reference to the value/object. Same thing here. Something needed a reference to this at that moment in time, hard to know what it is since you id not show all the code. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – epascarello Jan 29 '20 at 14:09

3 Answers3

1

When you assign a variable to a value without using var it refers to global variable. So if you are assigning this to ctrl it means the your are assigning Window obecjt this to a global variable `ctrl.

So when you compare ctrl with this (again Window) object, it is same since you are matching after function execution.

Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
1

var a = function() {

 var THIS = this;
 this.s = "Hello World";
 this.runMe = function() {
  window.setTimeout(function() {
   console.log(this.s);
  }, 100);
 }
 
}

var a2 = function() {

 var THIS = this;
 this.s = "Hello World";
 this.runMe = function() {
  window.setTimeout(function() {
   console.log(THIS.s);
  }, 100);
 }
 
}

b = new(a);
b.runMe();

b2 = new(a2);
b2.runMe()

Outputs:

undefined

Hello World

Class a (object b) returns undefined because that this is in the scope of the callback.

Class a2 (object b2) returns Hello World because that this belongs to the class a2.

GetSet
  • 1,511
  • 2
  • 10
  • 13
0

In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called.

You assign THIS to a variable so you save this value.

Read more: https://medium.com/tech-tajawal/javascript-this-4-rules-7354abdb274c

Armin
  • 373
  • 2
  • 13