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

153
Views
Difference between super and this while calling a function in sub class in js

class A {
  data1 = 1;
  constructor(){
    this.data2 = 2;
  }
  test() { console.log(this) }
}
class B extends A {
  constructor() {
    super();
  }
  funcA() { this.test() }
  funcB() { super.test() }
}
let foo = new B()
foo.funcA();
foo.funcB();

what's the difference between funcA() and funcB() while calling, or they are exactly the same thing? BTW, what's the difference between data1 and data2 declared in and out the constructor, which is preferred

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

With this.test(), you reference the instance. No test property exists directly on the instance, so as with standard prototypal inheritance, the prototype object is examined for the property. This prototype is A.prototype, which does have a test property, so that gets called.

With super.test(), you instead start looking for the test property on the superclass - A.prototype, which is found immediately and called.

If you had a test method on B as well, you'd see the difference.

class A {
  data1 = 1;
  constructor(){
    this.data2 = 2;
  }
  test() { console.log('a') }
}
class B extends A {
  constructor() {
    super();
  }
  test() {
    console.log('b');
  }
  funcA() { this.test() }
  funcB() { super.test() }
}
const foo = new B()
foo.funcA();
foo.funcB();

BTW, what's the difference between data1 and data2 declared in and out the constructor, which is preferred

It's up to you. Though, class fields (assigning outside of the constructor) are slightly more concise (especially if your constructor doesn't contain anything else) but less supported - if you want to use them, make sure to transpile your code.

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!