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

What is the process for assigning a function and its arguments as a callback in programming?

Here is a code snippet for your consideration: $scope.delete=function(){ foo('x',3); }; How can we improve the clarity of this code snippet when the callback function contains only one line that calls another function? It's important ...

The expansion animation for the Nextjs/React accordion box did not work as expected when utilizing tailwindcss

I am currently working on creating an animation for a collapsible box (accordion). My goal is to have the child component initially hidden with display:none. When I hover over the parent component, the child should be revealed and the dimensions of the pa ...

By utilizing the HTML element ID to retrieve the input value, it is possible that the object in Typescript may be null

When coding a login feature with next.js, I encountered an issue: import type { NextPage } from 'next' import Head from 'next/head' import styles from '../styles/Home.module.css' import Router from 'nex ...

Despite reaching a video readystate of 4 in HTML5, the video still hangs and does not play smoothly

Using html5, I am currently working with video and audio. I have encountered an issue where sometimes the video hangs even after its readyState === 4. The cause of this problem is unclear to me. I aim for a solution where if the video's readyState = ...

Challenges with Angular 4 service initialization

Having trouble with my authentication service. The constructor is being called 259 times when making an HTTP request, but only once when the call is removed. I am using a shared module to provide a unique instance of the service. Angular version: 4.4.4 C ...

Learn how to effectively declare data as global within Angular2 or Typescript

I am facing an issue with fetching the id inside the Apiservice despite being able to get it in the console. Can anyone provide assistance on how to solve this problem? TS: deleteProduct(index,product) { var token = this.auth.getAccessTokenId(); ...

Creating intricate JavaScript objects for JSON API integration can be accomplished by following these steps:

Here is a sample JSON structure used for querying an API: "order_items": [ { "menu_item_id": "VD1PIEBIIG", "menu_item_name": "Create Your Own", "modifiers": [ { "modifier_id ...

Real-time updates for UI data in Next.js Firestore are not being reflected

I'm currently working on implementing real-time changes using nextjs and Firebase Firestore. However, I've noticed that I still need to refresh the page in order for the updates to be visible. const [getUsers, setUsers] = useState(""); const che ...

Getting unique results from a knex.js INNER JOIN operation

Two tables, metadata and view_events, each have columns for config_id and config_type. The goal is to retrieve all unique view_events based on a user's email address, distinct by config_id and config_type, ordered by timestamp in descending order, lim ...

"Trouble arises with the match() function in relation to email regex validation

After retrieving the HTML content from a website with my function, I am using String.prototype.match along with a regex rule to extract email addresses from that page. However, the issue is that I am receiving a line that matches the regex but does not con ...

utilizing ajax to submit data with checkbox option

<html> <body> <input type="checkbox" checked="checked"> </body> </html> I am looking for a solution to pass the value of a checkbox as either 1 or 0 depending on its selection status. When the checkbox is checked, I want to s ...

A more efficient method for creating a nested array of distinct values using JavaScript

The scenario: My website has a complex html table structure to showcase hierarchical data, with the ability for users to toggle visibility of individual rows. Each row is identified by a dom id consisting of a level number and primary key specific to that ...

The way an event can be outrun or vanish due to another event

let bar = new function(){ $scope.MessageSpan="Item added successfully";} When the Add button is clicked, the above function is invoked. However, if I want to hide this message when any other button is clicked, I would have to update the span text for all ...

Sending data using formData across multiple levels of a model in Angular

I have a model that I need to fill with data and send it to the server : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode ...

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 ...

IE11 experiences frequent crashes when running a web application utilizing the Kendo framework and JavaScript

I am experiencing difficulties with my ASP.NET MVC application that utilizes Kendo UI and jQuery. Specifically, when using Internet Explorer 11, the browser crashes after a short period of usage. The crash does not seem to be linked to any specific areas o ...

Dynamic autocomplete feature with AJAX integration for filtering in Flask

Looking for some guidance on creating an HTML form with two input fields. Check out the HTML template code below: <form role="form" action="/cities/" method="get" autocomplete="on"> <label for="#input1"><strong>Country:</strong&g ...

Steps for showing personalized validation error messages in Angular 7

Is there a way to highlight the input field of a form with a red border and display the message Password is invalid when a user types in a password that does not match the set password? I have managed to see the red border indicating an error when I enter ...

Sending a request from JavaScript to C# methods using AJAX, with no expected response, within an ASP.NET MVC framework

Setting up the Environment: <package id="jQuery" version="3.2.1" targetFramework="net45" /> <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" /> Recently, I encountered an issue while trying to send a request from one ...

Having difficulty maintaining trailing zeroes in decimals after converting to float in Angular

I need assistance with converting a string to float in Angular. Whenever I use parseFloat, it seems to remove the zeros from the decimal values. How can I ensure that these zeros are retained with the numerical values? The example below should provide more ...