https://bigfrontend.dev/quiz/inherit-getter-setter
What does the code snippet below output by console.log
?
let val = 0;
class A {
set foo(_val) {
val = _val;
}
get foo() {
return val;
}
}
class B extends A {}
class C extends A {
get foo() {
return val;
}
}
const b = new B();
console.log(b.foo);
b.foo = 1;
console.log(b.foo);
const c = new C();
console.log(c.foo);
c.foo = 2;
console.log(c.foo);
console.log(b.foo);
let val = 0;
class A {
set foo(_val) {
val = _val;
}
get foo() {
return val;
}
}
class B extends A {}
class C extends A {
get foo() {
return val;
}
}
const b = new B();
console.log(b.foo); // 0
b.foo = 1;
console.log(b.foo); // 1
const c = new C();
console.log(c.foo); // 1
c.foo = 2;
console.log(c.foo); // 1
console.log(b.foo); // 1
The reason that both c.foo
and b.foo
return 1
after setting c.foo
to 2
is that when we override the get
method of an attribute in an inherited class, set
method must also be overridden, and vice versa, because if an object has own property, this property will be used and not an inherited one.
let val = 0;
class A {
set foo(_val) {
val = _val;
}
get foo() {
return val;
}
}
class C extends A {
get foo() {
return val;
}
set foo(_val) {
super.foo = _val;
}
}
const c = new C();
console.log(c.foo); // 0
c.foo = 2;
console.log(c.foo); // 2