Difference between super and this while calling a function in sub class in js
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.