1

I am new to Javascript, can someone please help me understand if there is a fundamental difference between these 2 ways

First where I use this to call a function defined inside the var itself


var TxMmm={
  name: {},
  timeout: 2000,
  testFunc1: function(){
    console.log("testFunc1");
    testFunc2();
    this.testFunc3();
  },
  testFunc3: function(){
    console.log("Test func3");
  }
}
function testFunc2(){
  console.log("This is func2 is outside var");
}

v/s Below where I use the var TxMmm to call function defined inside itself.


var TxMmm={
  name: {},
  timeout: 2000,
  testFunc1: function(){
    console.log("testFunc1");
    testFunc2();
    TxMmm.testFunc3();
  },
  testFunc3: function(){
    console.log("Test func3");
  }
}
function testFunc2(){
  console.log("This is func2 is outside var");
}
user620339
  • 851
  • 3
  • 20
  • 42
  • Try changing `var TxMmm` -> `var TxMmm2` and see how both work afterwards. Next try eliminating the variable entirely. – VLAZ May 19 '22 at 16:56
  • There are some good points to be made about this. I wonder if they've already been made in an SO answer somewhere. – T.J. Crowder May 19 '22 at 16:59
  • Related, but not (I don't think) targets for closure: [1](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work), [2](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – T.J. Crowder May 19 '22 at 16:59

1 Answers1

0

In that specific code there isn't that much difference, because the object is a singleton. Some differences:

  1. In your first code block using this, this could refer to something other than the TxMmm object in (say) testFunc1, depending on how testFunc1 is called. For instance, this would fail:

    const fn = TxMmm.testFunc1;
    fn();
    

    But in your second code block, TxMmm will refer to the object (unless the next point comes into play), so that would work. More here and here.

  2. If someone does:

    const x = TxMmm;
    TxMmm = somethingElse;
    x.testFunc1();
    

    ...your first code block using this will keep working, because this is set by how testFunc1 is called. But your second code block using TxMmm would fail, because TxMmm doesn't point to the object anymore.

  3. It almost never matters (seriously, very nearly never), but in your second code block, when you use TxMmm, the JavaScript engine has to look up that identifer to find it in the enclosing scope. Your code using this is able to resolve it immediately (since those aren't arrow functions), which in very rare situations can be faster in a noticeable way.

For non-singleton objects, this can be very important, since it tells the code which object's properties to use.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875