Error! Attempting to assign a value to property 'getName' of an undeclared object

 <script>  
    var Employee = new function(name)
    {
     this.name=name;
    }
    Employee.prototype.getName = function()
    {
      return this.name;
    }

    var PermanenetEmployee = new function(annualsalary)
    {
    this.annualsalary=annualsalary;
    }
    var employee = new Employee("rahul");
    PermanenetEmployee.prototype = employee;
    var pe = new PermanenetEmployee(5001);
    document.write(pe.getName());



    </script> 

This code showcases an implementation of inheritance in JavaScript. The goal is to print the name of the employee, in this case, "rahul." However, I am encountering an error: Uncaught TypeError: Cannot set property 'getName' of undefined (anonymous function). How can I resolve this issue?

Employee.prototype.getName = function()
        {
          return this.name;
        }

Answer №1

Here is the issue presented:

var Employee = new function(name)
// ------------^^^
{
 this.name=name;
}

(The same applies to PermanenetEmployee.)

The unnecessary use of new is the problem here. It actually invokes the function, whereas you should call it later as done when assigning to employee.


It's important to note that the way you are setting up inheritance between them is not ideal. To correctly make PermanenetEmployee "subclass" Employee, do the following:

PermanenetEmployee.prototype = Object.create(Employee.prototype);
PermanenetEmployee.prototype.constructor = PermanenetEmployee;

Rather than:

var employee = new Employee("rahul");
PermanenetEmployee.prototype = employee;

...and then have PermanenetEmployee receive name and pass it to Employee:

var PermanenetEmployee = function(name, annualsalary) {
    Employee.all(this, name); // <====
    // ...
};

...or better yet, utilize ES2015 ("ES6") class (with transpiling if necessary, e.g., Babel).

Below is a corrected setup along with fixing the typo in PermanenetEmployee:

var Employee = function(name) {
    this.name = name;
};
Employee.prototype.getName = function() {
    return this.name;
};

var PermanentEmployee = function(name, annualSalary) {
    Employee.call(this, name);
    this.annualSalary = annualSalary;
};

// Establish subclass
PermanentEmployee.prototype = Object.create(Employee.prototype);
PermanentEmployee.prototype.constructor = PermanentEmployee.prototype;

PermanentEmployee.prototype.getAnnualSalary = function() {
    return this.annualSalary;
};

// Implementation
var pe = new PermanentEmployee("Rahul", 5001);
console.log(pe.getName());
console.log(pe.getAnnualSalary());

And using ES2015:

class Employee {
    constructor(name) {
        this.name = name;
    }
    getName() {
        return this.name;
    }
}

class PermanentEmployee extends Employee {
    constructor(name, annualSalary) {
        super(name);
        this.annualSalary = annualSalary;
    }

    getAnnualSalary() {
        return this.annualSalary;
    }
}

// Implementation
var pe = new PermanentEmployee("Rahul", 5001);
console.log(pe.getName());
console.log(pe.getAnnualSalary());

Again, remember that transpilation may be required to use that syntax in real-world scenarios for now.

Answer №2

If you're looking to implement inheritance in JavaScript, here's a pattern that can be quite useful.

Start by defining the base prototype:

Person = function () {
};
Person.prototype = {
    getName: function () {}
};

Next, create the prototype that will inherit from the base:

Student = function () {
    Person.call(this);
};

Student.prototype = Object.create(Person.prototype);
Student.constructor = Student;

Student.prototype.bar = function() {}

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

Obtain data without issuing a new query in flexigrid

I am encountering an issue with flexigrid where the initial page load triggers a query, and then when I either (1) adjust the sort order or (2) navigate to the next page, it runs a new query with different parameters, resulting in slow performance. I am s ...

Reasons for storing `https.get()` inside a request constant in Node.js

When using simple javascript, any content written to the console is displayed on the console itself. An example would be as follows: const name = "david"; This will display david in the console. However, in Node.js, if I store a request in a const varia ...

Ways to alter the color of a link after clicking it?

Is there a way to change the link color when clicking on it? I have tried multiple approaches with no success. The links on this page are ajax-based and the request action is ongoing. <div class="topheading-right"> <span> ...

What are some strategies for efficiently displaying a large amount of data on a screen using Javascript and HTML without sacrificing performance?

Imagine having a hefty 520 page book with over 6,200 lines of text ranging from 5 to 300 characters each. The challenge lies in efficiently displaying this content on the screen for users to read without causing lag or performance issues. Attempting to re ...

Asp.net isn't cooperating with Jquery Ajax Call

I've tried multiple solutions, but nothing seems to be working. I'm attempting a simple Ajax call using Jquery in Visual Studio 2019, but the code is not hitting the Ajax call. Here's the snippet of my code: <script src="Scripts/jqu ...

What could be causing my middleware to run twice?

A custom middleware was created in express.js/node.js to handle session checking. If a user ID is found in the session, it displays the user's menu; otherwise, it shows the default menu. For every page request, an ID check is performed and the user d ...

I'm trying to figure out how to save a Mongoose query and then pass it as a parameter to render an EJS page. How can I achieve this

I'm currently in the process of constructing an admin dashboard, and one feature I want to include is displaying mongoose data such as user information and recent tutoring sessions. However, I'm facing challenges when it comes to saving this data ...

Improving Performance in Vue by Reducing `$set` Usage

Sharing my code snippet below <div v-for="namespace in chosenNamespaces" v-bind:key="namespace.id"> <!-- Select the Parameter --> <select @change="updateParameter($event, namespace.id)" v-model="currParameterValues[na ...

Utilizing Bootstrap's Multi-Grid System

I am currently working on implementing a Bootstrap grid design that resembles pic1.jpg. However, I am facing challenges in achieving the desired layout, as pic2.jpg shows the current scenario. Below, I have shared the code I am using. pic1.jpg :- ! pic2. ...

Having npm start is causing an error to be displayed

I am encountering an issue when I try to start 'npm' on my mean.js application. The error message is related to a missing file called '.csslintrc'. Below, I have included the terminal output as well as the snippet of code where the erro ...

Using JavaScript to send information to an external website

My website is built with HTML and JavaScript/jQuery. Is there a way to automatically fill out a form on an external page (let's say Google.com) after clicking on a link from my site? For instance, I'd like to click on a link that takes me to Goo ...

Utilizing TypeORM to selectively choose data in OneToMany relationships

I am looking to create a TypeORM query that pulls data from the database. Specifically, I want to retrieve all clients who have made a purchase but have not initiated a return. Here is the structure of the database: Clients: Id (Int, primary column) Purc ...

Arranging an upgrade within a task management app

I'm currently in the process of developing a task management app with AngularJS, Node, Express, and MongoDB. Everything seems to be falling into place except for the update functionality. I'm struggling with implementing this feature, especially ...

Uncovering the Mystery Behind the Repetitive Execution of useEffect in Next.js

I am working on a Time Tracking feature for my Next.js application. In the ./app/components/TimeTracking.tsx file, I have implemented the following component: 'use client'; import React, { useEffect, useState } from 'react'; import { u ...

Issue with rendering in sandbox environment versus localhost

Here's a dilemma I'm facing - I have some HTML code on my localhost that looks like this: <div> <p>Go to: <a href="www.foobar.com">here</a></p> </div> On localhost, the output is "Go to: here" with 'he ...

I am having issues with sendKeys and click() functions in my code. I am unable to access the elements using Protractor's javascript

<input class="form-control validation-field ng-dirty ng-touched ng-invalid" placeholder="Password" type="password"> Despite using the element to retrieve it, I am unable to send keys and no error message is displayed. This issue persists in both Fir ...

storing information in local storage is not optimal in terms of speed

Within my jQuery mobile app, I have two pages labeled as #list and #show. The #list page contains multiple items with unique IDs. When a user clicks on item number 5, the corresponding ID is stored in localStorage and they are redirected to the #show page. ...

Tips to center a circular progress bar in Material UI

Does anyone know how to properly center-align a circular progress bar in a login form using material UI? I'm having trouble with it not being positioned correctly: screenshot {isLoading && <CircularProgress />} {user?.ema ...

Dygraph - emphasize the area below the line exclusively or use a multi-color background based on the Y axis value

I am currently using Dygraph to display students' attendance data. I have implemented a feature that highlights low attendance areas for specific months, inspired by this example on the dygraph site: here. However, in my implementation, the highlight ...

Exploring the possibilities of retrieving Cognitive data from Lambda events using Node.js and Typescript

import { APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEvent, any } from 'aws-lambda'; export async function myHandler(event: APIGatewayProxyEvent, context: APIGatewayEventDefaultAuthorizerContext,): Promise<any> { console.log( ...