JavaScript prototypal inheritance concept

During my free time, I like to dabble in JavaScript, but I’m currently struggling with this particular topic.

var person = new Person("Bob", "Smith", 52);
var teacher = new Teacher("Adam", "Greff", 209);

function Humans(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

function Person(firstName, lastName, age) {
  Humans.call(this, firstName, lastName);
  this.age = age;
}

Person.prototype = Object.create(Humans.prototype);

Person.prototype.fullDetail = function() {
  return this.firstName + " " + this.lastName + " " + this.age;
};


function Teacher(firstName, lastName, roomNumber) {
  Humans.call(this, firstName, lastName);
  this.room = roomNumber;
}

Teacher.prototype = Object.create(Humans.prototype);

Teacher.prototype.fullDetail = function() {
  return this.firstName + " " + this.lastName + " " + this.room;
};

// Here we call the fullDetail method of the person object
person.fullDetail();

Could anyone explain why person.fullDetail(); isn’t executing properly?

If you could provide some feedback and suggestions through your version of the code, it would be greatly appreciated. Thank you!

Answer №1

One common mistake is creating objects before defining their prototypes.

For example, when you write:

var person = new Person ("Bob", "Smith", 52);

you are essentially creating an object based on the current definition of Person. Later in your code, if you change the prototype of Person, it affects all instances of that object.

Person.prototype = Object.create(Humans.prototype);

To solve this issue, make sure to define your objects after re-assigning the prototype.

function Humans(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

function Person(firstName, lastName, age) {
  Humans.call(this, firstName, lastName);
  this.age = age;
}

Person.prototype = Object.create(Humans.prototype);

Person.prototype.fullDetail = function() {
  return this.firstName + " " + this.lastName + " " + this.age;
};


function Teacher(firstName, lastName, roomNumber) {
  Humans.call(this, firstName, lastName);
  this.room = roomNumber;
}

Teacher.prototype = Object.create(Humans.prototype);

Teacher.prototype.fullDetail = function() {
  return this.firstName + " " + this.lastName + " " + this.room;
};

var person = new Person("Bob", "Smith", 52);
var teacher = new Teacher("Adam", "Greff", 209);
console.log(person.fullDetail());

Answer №2

Yes, the issue arises because the Person prototype does not have a FullDetail method when creating a person object.

To resolve this problem, rearrange the order of your object creation by first adding methods to the prototype before creating the person object.

Take a look at this code snippet:

var teacher;
var person;
function Humans(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

function Person(firstName, lastName, age) {
  Humans.call(this, firstName, lastName);
  this.age = age;
}

Person.prototype = Object.create(Humans.prototype);

Person.prototype.fullDetail = function() {
  return this.firstName + " " + this.lastName + " " + this.age;
};

person = new Person("Bob", "Smith", 52);

function Teacher(firstName, lastName, roomNumber) {
  Humans.call(this, firstName, lastName);
  this.room = roomNumber;
}

Teacher.prototype = Object.create(Humans.prototype);

Teacher.prototype.fullDetail = function() {
  return this.firstName + " " + this.lastName + " " + this.room;
};
teacher= new Teacher("Adam", "Greff", 209);
console.log(person.fullDetail());
console.log(teacher.fullDetail());

I hope this solution helps you with your programming issue.

Answer №3

It appears that the issue arises from creating the person and teacher objects without defining their functions in the prototype. To fix this problem, you can follow the corrected code below:

function Humans(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

function Person(firstName, lastName, age) {
  Humans.call(this, firstName, lastName);
  this.age = age;
}

Person.prototype = Object.create(Humans.prototype);

Person.prototype.fullDetail = function() {
  return this.firstName + " " + this.lastName + " " + this.age; 
};


function Teacher(firstName, lastName, roomNumber) {
  Humans.call(this, firstName, lastName);
  this.room = roomNumber;
}

Teacher.prototype = Object.create(Humans.prototype);

Teacher.prototype.fullDetail = function() {
  return this.firstName + " " + this.lastName + " " + this.room; 
};
var person = new Person ("Bob", "Smith", 52);
var teacher = new Teacher ("Adam", "Greff", 209);

console.log(person.fullDetail());
( ͡° ͜ʖ ͡°)

Answer №4

If you have moved on to ES6, consider utilizing the new class syntax as shown below:

class ExampleBaseClass {
    // Implement functionality here...
}

class ExampleClass extends ExampleBaseClass {
    // Add additional functionality here...
    // You can also access methods from ExampleBaseClass in this class.
}

For more information, check out: https://www.sitepoint.com/understanding-ecmascript-6-class-inheritance/

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

Updating with MySQL can only manipulate integers and not strings

Setting up seems simple, but the number of potential causes is overwhelming for someone new to programming like me: In JavaScript, I define and later call: function dbUpdate(x, y, z) { $.ajax({ url: 'php/dbUpdate.php', type: ...

Is there a way to access the value of a variable within a loop inside a function and store it in a global variable?

I am struggling to retrieve the value of a variable after it has passed through a loop. I attempted to make it a global variable, but its value remains unchanged. Is there any way to achieve this? Below is my code snippet where I am attempting to access t ...

"Utilizing the __proto__ property in Express.js for handling request

One issue that I've encountered is with the request.body generated by the express.urlencoded() middleware. Sometimes, it adds "__proto__" at the end of the request.body object, which makes it impossible to directly use it to initialize a mongoose mode ...

Determining the height of child elements within a React component

One challenge I'm facing inside a React component is the need to calculate the total height of my child containers, specifically the three h3 elements, in order to accurately determine the height of my parent div during a transition animation. While I ...

When a table is required, .data() will provide a string

Within my HTML code, there is a table structure defined as follows: <table id="table" data-keys="{{keys}}"> Here, the keys variable represents an array (as I later iterate through it using {% for k in keys %}). However, when I t ...

How to implement and utilize a history-object interface in React with Typescript?

Can you help me with setting up an interface for a history object in my component? Currently, it is typed as any and I want to type it appropriately. Object: Here's the code snippet: import React, { useState } from 'react'; import { Row, C ...

Is there a way to prevent text from overlapping a Material UI React Textfield when it is scrolled up and set to position sticky?

Scenario: In my chat application, I have the chat displayed in the middle of the screen with a sticky textfield at the bottom. My goal is to ensure that when users scroll through the chat messages, the textfield remains at the bottom but appears on top of ...

Exploring the World with the vue-i18n Plugin

Recently, I have integrated translation into my app and now I am looking to implement a button event that allows users to change the language on the home page. For this task, I referred to two tutorials: Localization with Vue and Localization with Vue Tut ...

Navigate from Product Listing to Product Details Page by utilizing JSON data with ReactJS

I have successfully retrieved the initial level of JSON Data, which consists of objects/Product List. My objective is to implement a functionality where clicking on the "View Details" button will redirect to the respective product detail page, similar to ...

Nested Angular click events triggering within each other

In my page layout, I have set up the following configuration. https://i.stack.imgur.com/t7Mx4.png When I select the main box of a division, it becomes highlighted, and the related department and teams are updated in the tabs on the right. However, I also ...

Create a hierarchical tree structure using a string separated by dots

I am struggling with organizing a tree structure. :( My goal is to create a tree structure based on the interface below. export type Tree = Array<TreeNode>; export interface TreeNode { label: string; type: 'folder' | 'file'; ...

Execute sequential animations on numerous elements without using timeouts

I'm currently working on developing a code learning application that allows users to write code for creating games and animations, similar to scratch but not block-based. I've provided users with a set of commands that they can use in any order t ...

The Ajax Control Upload consistently defaults to the default value and disregards any text input selected from the drop-down list

On my website, I have implemented an ajax control upload event that allows users to upload a zip file and then unzip it using zlib. The folder name for unzipping is created based on the selection from a dropdown list. However, I am facing some issues where ...

Generating hyperlink regions dynamically

I am looking to create an image with a link map that will contain multiple areas that need to be updated frequently. Instead of constantly recreating the areas every few seconds, I want to generate them only when the user clicks on the image. I initially ...

Unable to change data in table TD using AJAX and PHP received JSON array

I am currently facing an issue with a PHP-AJAX script that is responsible for deleting financial rows from a table. The PHP script is functioning correctly and successfully deleting the rows. However, the problem arises within the success function of the A ...

Angular 2 template format standard

Every Angular 2 example I encounter seems to place the template within the component decorator. import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: '<h1>Hello world</h1>' }) e ...

What are some ways to implement the 'charCodeAt' method within a for loop effectively?

Currently, I am working on developing a hangman game in JavaScript to enhance my coding skills. One task that I am facing is extracting the keyCode of a character at a particular position within an array. To achieve this, I have been using the 'charCo ...

Is there a way to showcase AJAX responses in the exact sequence they were dispatched, all without relying on queuing or synchronous requests?

I'm facing a challenge with sending out multiple getJSON() requests to a remote server in order to retrieve images. The issue is that the responses arrive asynchronously, causing them to be displayed in a mixed-up order. While I could make the reques ...

Code activates the wrong function

Below is a snippet of HTML and JS code for handling alerts: HTML: <button onclick="alertFunction()">Display Choose Option Modal</button> <button onclick="alertFunction2()">Display Veloce Modal</button> JS: function alertFunct ...

Manipulate HTML elements using JavaScript when a key is being held down

I'm currently developing a simple game using vueJS for the frontend. I have successfully created all the necessary objects and now my goal is to enable their movement when a key is pressed. However, I am facing an issue where the object only moves on ...