'How to let newB access getX function?

I think that I set everything correctly by using the call function to pass variable x from parent b, but still receive the error which is "newB.getX is not a function". I am a beginner please give me some hints and explanation, thank you.

 const a = function(x) {
  this.x = x
}

a.prototype = {
  getX() {
    return this.x;
  }
}

const b = function(x, y) {
  a.call(this, x);
  this.y = y;
}

b.prototype = {
  getY() {
    return this.y;
  }
}

const newB = new b('x', 'y');
console.log('question 5:', newB.getX());
console.log('question 5:',newB.getY());


Solution 1:[1]

Doing a.call(this, x); only runs a's constructor, which only assigns a property to the instance. It doesn't change any of the internal prototypes. newB's prototype chain remains:

instance (has property x) <- b.prototype (has getY property) <-Object.prototype

a.prototype is not in the chain, so getX is not visible on the instance.

I suppose you could iterate over all of a's prototype properties and assign them to the instance.

const a = function(x) {
  this.x = x
}

a.prototype = {
  getX() {
    return this.x;
  }
}

const b = function(x, y) {
  a.call(this, x);
  for (const [key, prop] of Object.entries(a.prototype)) {
    this[key] = prop;
  }
  this.y = y;
}

b.prototype = {
  getY() {
    return this.y;
  }
}

const newB = new b('x', 'y');
console.log('question 5:', newB.getX());
console.log('question 5:',newB.getY());

Or do it in a's constructor

const a = function(x) {
  this.x = x;
  this.getX = () => this.x;
}

const b = function(x, y) {
  a.call(this, x);
  this.y = y;
}

b.prototype = {
  getY() {
    return this.y;
  }
}

const newB = new b('x', 'y');
console.log('question 5:', newB.getX());
console.log('question 5:',newB.getY());

Or use a class, which is probably the preferred modern method of subclassing (over manually extending functions)

class a {
  getX = () => this.x;
  constructor(x) {
    this.x = x;
  }
}
class b extends a {
  getY = () => this.y;
  constructor(x, y) {
    super(x);
    this.y = y;
  }
}

const newB = new b('x', 'y');
console.log('question 5:', newB.getX());
console.log('question 5:',newB.getY());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance