Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

79
Views
Javascript this vs using same var name within itself

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");
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!