Skip to content

Latest commit

 

History

History
116 lines (88 loc) · 1.7 KB

58.inherit-getter-setter.md

File metadata and controls

116 lines (88 loc) · 1.7 KB

58. inherit getter setter

Problem

https://bigfrontend.dev/quiz/inherit-getter-setter

Problem Description

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);

Answer

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

Explanation

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

Reference

Override a setter, and the getter must also be overridden