JavaScript's prototypical inheritance model allows objects to inherit properties and

Exploring javascript's prototypical inheritance and object-oriented programming is new to me. I attempted to create a base object called Account and then inherit the CheckingAccount from it. Below is my code snippet.

function Account(fName, lName) {
   this.firstName = fName;
   this.lastName = lName;

 }

 Account.prototype.balance = function() {
    console.log("This is the balance");
 }

 function CheckingAccount() {

    this.salary = 10000;
 }

 CheckingAccount.prototype = Object.create(Account.prototype);

 let account = new Account("John", "Doe");
 let checking = new CheckingAccount();
 CheckingAccount.balance();

Upon running this in Visual Studio, an error message pops up: "Uncaught TypeError: CheckingAccount.balance is not a function". Any guidance on resolving this issue would be highly appreciated.

Answer №1

It is advisable to call the method on the instance rather than the Class object (e.g., checking instead of CheckingAccount). Additionally, remember to modify the constructor accordingly. For more information, you can consult the MDN documentation.

You can view the changes implemented below:

function Account(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.salary = 0;
}

Account.prototype.balance = function() {
    return this.salary;    // you may need additional properties besides salary
}

function CheckingAccount() {
    this.salary = 10000;
}

CheckingAccount.prototype = Object.create(Account.prototype);
// Update the constructor
Object.defineProperty(CheckingAccount.prototype, 'constructor', {
    value: CheckingAccount,
    enumerable: false, // prevents it from appearing in 'for in' loop
    writable: true
});

let account = new Account("John", "Doe");
let checking = new CheckingAccount();

console.log('account balance:',      account.balance())
console.log('checking balance:',     checking.balance())
console.log('account constructor:',  account.constructor);
console.log('checking constructor:', checking.constructor);

Answer №2

To implement this functionality in ES6, use the `class` keyword properly. Below is an example showcasing two classes: Account and Chequing. The Account class contains properties like `balance`, `deposit`, and `showBook` functions, while the Chequing class extends the Account class and adds a `writeCheque` function. Despite being a child class, instances of Chequing can still access all parent class functions due to their inheritance from Account.

class Account {
  constructor(name) {
    this.name = name;
    this.amount = 0;
  }
  balance() {
    return this.amount
  }
  deposit(sum) {
    this.amount += sum;
  }
  showBook() {
    console.log("-------------------------");
    console.log("Account for",this.name);
    console.log(`Balance: $${this.amount}`);
  }
}

class Chequing extends Account {
  constructor(name) {
    super(name);
    this.cheques = [];
  }
  writeCheque(sum, to) {
    this.amount -= sum;
    this.cheques.push({number: this.cheques.length+1, recipient: to, amount: sum});
  }
  showBook() {
    super.showBook();
    if (this.cheques.length > 0) {
      console.log("Cheque activity:");
      for (const cheque of this.cheques) {
        console.log(`  ${cheque.number}: $${cheque.amount} paid to ${cheque.recipient}`);
      }
    }
    else console.log("No cheques have been written");
  }
}

const ch1 = new Chequing("Mary Jones");
ch1.deposit(1000);
ch1.showBook();
ch1.writeCheque(95, "Bob Smith");
ch1.writeCheque(485, "Ritz Hotel");
ch1.showBook();

Answer №3

Account and CheckingAccount are both classes. Instances of these classes are referred to as the account and checking.

If you want the CheckingAccount class to inherit from the Account class, you should do the following:

CheckingAccount.prototype = Object.create(Account.prototype);

This action assigns CheckingAccount's prototype object to Accounts' prototype object.

The CheckingAccount function does not have a balance property (note: functions are first-class objects in JavaScript); only a prototype property is present. However, the balance property, which is also a function, can be found within the object that Account's prototype property points to.

The balance() function can be accessed from:

  • The Account.prototype
  • The CheckingAccount.prototype (due to your use of the Object.create function)
  • Any instances created from both of these classes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Contrasting the disparities between creating a new RegExp object using the RegExp constructor function and testing a regular

Trying to create a robust password rule for JavaScript using regex led to some unexpected results. Initially, the following approach worked well: const value = 'TTest90()'; const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2 ...

Bootstrap4 does not support the <button> element

How can I achieve a 'collapse icon' floated to the left followed by Copyright © using Bootstrap 4? I've looked at similar questions on this topic, but none seem to provide a direct answer. Other questions contain different code with ob ...

Vue function that inserts <br> tags for addresses

My Vue filter retrieves and combines address details with a , Vue.filter('address', (address, countryNames = []) => { const formattedAddress = [ address?.name, address?.company, address?.add1, address?.add2, address?.town ...

Change the value of the material slide toggle according to the user's response to the JavaScript 'confirm' dialogue

I am currently working on implementing an Angular Material Slide Toggle feature. I want to display a confirmation message if the user tries to switch the toggle from true to false, ensuring they really intend to do this. If the user chooses to cancel, I&ap ...

The function is defined, but it cannot be set to null

Having trouble understanding this error message "Cannot set properties of null." I'm attempting to update the innerHTML with the output text from four functions that my button triggers. However, it seems to be stopping at the first function now even t ...

After the ajax request is made in React JS, the column vanishes from the screen

Upon querying a node.js server's PostgreSQL database, I receive specific data that needs to be displayed in two separate tables. Each table consists of two columns. However, after the AJAX call, only the first column is being populated in the first ta ...

Finding the source of the err.kind expression in the MERN stack: Unraveling the mystery

Recently, I've been delving into the world of MERN stack development and came across an interesting technique for Error Handling in a tutorial. The tutorial showcased various expressions that can be used to identify different types of errors being thr ...

Making a Zoom effect using p5.js

I have searched for a solution to this question multiple times, but none of the answers I came across seem to work for me. Currently, I am able to allow the user to scale an image with a simple scale(factor) call. However, now I am attempting to implement ...

Django: Error - < found where unexpected

Using a combination of Django and jQuery, I have implemented a file upload feature with AJAX. Everything seems to be working correctly - the files are successfully uploaded, reflected in the database, and stored on the server. However, upon completion of t ...

How to toggle classes on specific items generated with Vue JS's v-for directive

I have a list rendering using the v-for directive in Vue.js. <li v-for="group in groupList" :key="group.id" @dragenter="toggleClass ...."@dragleave="toggleClass ...." > Content </li> My goal is to apply a class to the li el ...

Failure to specify the variable type can lead to the creation of automatic global variables

Recently, I stumbled upon this http://www.w3schools.com/js/js_scope.asp page which introduced me to the concept of "Automatic Global variables". Here is an example of how it works: // You can use carName variable here function myFunction() { carName ...

Tips on adjusting a position that shifts with changes in window size

Working on a website for my grandpa, I'm planning to include a small biker character that runs across the screen. When hovered over, he stops and advises "wear a helmet." The animation works well, but there's an issue with the positioning when th ...

Issue with styled-components not being exported

Issue: ./src/card.js There was an import error: 'Bottom' is not exported from './styles/cards.style'. card.js import React from 'react' import { Bottom, Color, Text, Image } from "./styles/cards.style"; fu ...

Is there a way for me to come back after all child http requests have finished within a parent http request?

I am currently utilizing an API that provides detailed information on kills in a game. The initial endpoint returns an ID for the kill event, followed by a second endpoint to retrieve the names of both the killer and the killed player. Due to the structur ...

How to retrieve the ID of the inserted record in Knex.js

I was trying to add a new note to the quoteNotes table. However, after inserting it and logging the response, I noticed that there was no record of the inserted note showing up. router.post('/:id/notes', (req, res) => { const {id} = req.para ...

Utilize the search bar within a JavaScript function

One issue I am facing is taking an input from a search box and using that value as a parameter for another function. However, every time I click the button, the global variable resets itself when the page refreshes. In my javascript code, this is what I h ...

Navigating a parameter within an AngularJS directive

I am currently developing a directive that acts as a wrapper for the freebase search widget using jQuery. This is my first attempt at creating a directive and I have encountered some challenges. Here are the functionalities I am aiming for: 1. The ability ...

The issue with the full postback in the updatepanel is triggered by utilizing JavaScript on the button's onclick event within

During my testing, I encountered an issue with buttons inside a repeater within an update panel. When adding asyncpostback triggers for the buttons using <Trigger></Trigger>, an error is generated indicating that the button could not be found. ...

The seamless flow of web design

Seeking guidance on creating a responsive web page. I have a functional website that looks great on my 13" MacBook, but encounters distortion at different screen sizes. What steps are necessary to ensure it appears crisp and appealing on any device? Should ...

Clear the modal form in Codeigniter and AJAX upon closing the edit modal

Having an issue with my modal form - when I open the edit modal, the data is fetched and that part works well. However, when I close the modal and try to add a new user, the data is automatically fetched again. Why is this happening? Shouldn't the for ...