How to display the name of the parent object using JavaScript's prototypal inheritance

I've been delving into JavaScript prototypal inheritance and the prototype property, and I decided to create a fiddle to gain a deeper understanding. However, I'm struggling to comprehend why my example isn't functioning as expected.

In the scenario below, I'm attempting to establish a hierarchy where the creation of an object reveals the name of its parent object. Despite my efforts, the logs consistently display "object".

One article clarified that prototype chaining operates in a way that if a property is absent in the object, it checks the prototype of the parent, continuing this process until reaching 'Object' and returning undefined if not found.

Feel free to check out the accompanying fiddle here: http://jsfiddle.net/hqozqd0m/

Object.prototype.cname = 'object';

function plant() {
    function parentname() { return this.cname; }
    return {
        parentname:parentname
    }
}
plant.prototype.cname = 'plant';

function tomato() { 
    function parentname() { return this.cname; }
    return {
        parentname:parentname
    }
}
tomato.prototype = new plant(); // <-- setting it to plant as parent

var p = new plant();
var t = new tomato();

console.log(p.parentname()); //object
console.log(t.parentname()); //object


updated code - same result

Object.prototype.cname = 'object';

function plant() {
    this.sayparentname = function() { console.log(cname); };
}
plant.prototype.cname = 'plant';

function tomato() { 
    this.sayparentname = function() { console.log(cname); };
}
tomato.prototype = new plant();

var p = new plant();
var t = new tomato();

p.sayparentname();
t.sayparentname();

Answer №1

Typically, a constructor function will update the object that is created by the new keyword, using statements like this.property = value, and will not return anything. In this case, the object created by new is the final result.

However, if the constructor function does return an object, that object will replace the one created by new. So, if you call new plant(), you will receive a basic Object instance instead.

To correct your code, you just need to structure it as follows:

function Plant() {
    function getName() { return this.name; }

    this.getName = getName;
}

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

Utilize dojo to manually trigger a window resize event

Is there a way to manually trigger the window resize event (the one that occurs when you resize your browser window) using Dojo? I need this functionality to dynamically resize my C3 Charts. I came across the on module in Dojo, which allows for listening ...

pdfMake introduces a page breaking effect when the canvas is utilized with the type "line"

Can anyone shed some light on why a canvas declaration with the type "line" is causing a page break in the generated PDF? I've tried removing all canvases and the page break disappears, but I can't identify the root cause. Any insights would be ...

The context of the Nuxt.js3 plugin loses its definition

Currently, I am working on a project that involves Nuxt.js3 and supabase integration. In my plugins/supabase.server.js file (I am still unsure whether using server or client is the best approach), I want to call "supabase = createClient(~~)" from index.vu ...

The process of styling with styled components in Mui - a guide to styling

Currently, I am facing challenges with styling and organization while working on a new react project with material ui and styled components. Despite researching best practices for styled components, I am still struggling to find an effective solution for s ...

What is the best approach to unit testing this React Component?

I have created a component that acts as a wrapper for another component. My question is, how should I approach unit testing for this component? Besides checking the state and method calls to ensure they update the state correctly. Other than rendering pro ...

Can Vue allow for the inclusion of HTML elements to store data seamlessly?

One example involves displaying array elements in an <ul>, with each element starting with <li> and ending with </li>. Here is the attempted code: clearedtaskslist: function(){ this.template='<ul>' for(let i=0;i<t ...

Converting JavaScript variable values to PHP variables by extracting the content of a textarea

Currently, I'm developing a data filtering mask which triggers when the button <input type="button" /> is clicked. In this process, I have: School classes (1, 2, 3, 4, 5) Sections (A, B, C....Z) Checkboxes for male and female sexes. This ma ...

Steps for creating a function to validate if two classes are identical

Currently, I am developing a memory game using JavaScript. One of the features I have implemented is toggling between two card faces by changing the class back and forth. Now, I am in the process of creating a function that will check if two game cards are ...

Use the .replace() method to eliminate all content on the page except for the table

Extracting a table from a page that has been loaded through .ajax() in queue.htm has proven to be challenging. I am attempting to utilize .replace(regex) in order to isolate the specific table needed, but the process is unfamiliar to me. $j.ajax({ ...

Attaching a buoyant div to the precise location of a different element

I have a unordered list (ul) with individual list items (li) that are displayed within a scrollable container. This means that only 8 list items are visible at a time, but you can scroll through them to see the others. Each list item (li) has an "edit" b ...

Error: WebView element type is not valid. A valid string was expected

Here is my basic React code : import React from "react"; import { Text, StyleSheet,View } from "react-native"; import { WebView } from 'react-native'; const App = () => { return( <WebView source={{ ...

Focusing on particular jQuery elements that share the same class names

I am facing an issue with dynamically generated divs that share the same class names. When I hover over the parent div (myDiv), I want to trigger an event and add a class to the myDiv child button. However, when I click on the parent div, I want to unbind ...

Tips for generating a <span> element using the img alt tag and inserting it following the <img> element

I have a set of images with 'alt' tags and I would like to extract the 'alt' tag for each img and create a <span> + alt tag + </span> line after each image. I am unsure of how to achieve this using jQuery. The desired outpu ...

The FormControlLabel radio button within the RadioGroup is experiencing difficulty in becoming selected

Utilizing a RadioGroup component to showcase a dynamic list of Radio options using FormControlLabel. The dynamic radio choices are appearing correctly on the screen and I can obtain the selected radio option through onChange in RadioGroup. However, after s ...

Improving an HTML list with JavaScript

My current project involves a JavaScript game similar to Scrabble. I want users to be able to create new words in the game, and have those words added to a list that is displayed on the page within a div element. However, I'm struggling to understand ...

Adding a loading event listener to an object in JavaScript: A step-by-step guide

I'm currently deep into developing a game using sprites in JavaScript. I've been trying to incorporate an event listener that verifies whether the sprite images have loaded before beginning the game. Employing object-oriented programming, I' ...

EJS: Dynamically linking CSS and JS files according to specific page conditions

Is there a way to conditionally call CSS/JS files based on specific page conditions in EJS? Can we use a flag from the router or base it on the URL in the EJS file? Note: The code below works perfectly when accessing the /editor page, but it will cause er ...

A tutorial on preventing backbone.js from automatically adding /# when a dialog is closed

Whenever I navigate back on my backbone page, it automatically adds /# to the URL. This results in loading an empty index page from the Rails home view when pressing back again. Disabling turbolinks fixed this issue for me. However, another problem arises ...

Implementing the Google Maps API into a React application to generate a customized route between two specified points

I'm currently developing a React application that is designed to display the distance between two points on a map. Although I successfully implemented this feature using JavaScript and HTML, I am facing challenges in converting it to React as I am re ...

Using Promise.all within an async function to handle variables inside of Lambda functions

I've spent the past couple of days trying to find a solution to this issue. I've simplified my code to mostly pseudo code for ease of understanding. What I'm struggling with is creating an async function that acts as a trigger for an SQS qu ...