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

156
Views
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());
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

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!