The inheritance of Object.prototype does not inherently guarantee correctness

I am currently working on a code that involves class inheritance. The Rabbit constructor is supposed to inherit methods from the Animal prototype in order to create an object named rabbit with Animal methods.

However, I am struggling to understand why the Rabbit constructor is not inheriting the Animal.prototype.name method. It is similar to the Animal.prototype.run method, but for some reason it is not functioning as expected...

    function Animal(name) {
      this.name = name;
      this.speed = 0;
    }
    
    Animal.prototype.run = function(speed) {
      this.speed += speed;
      console.log( this.name + ' run, speed ' + this.speed );
    };
    
    Animal.prototype.name = function(name) {
      this.name = name;
      console.log( 'Rabbit name ' + this.name );
    };
    
    Animal.prototype.stop = function() {
      this.speed = 0;
      console.log( this.name + ' stay' );
    };
    
    function Rabbit(name) {
      Animal.apply(this, arguments);
    }
    
    Rabbit.prototype = Object.create(Animal.prototype);
    Rabbit.prototype.constructor = Rabbit;
    
    Rabbit.prototype.jump = function() {
      this.speed++;
      console.log( this.name + ' jump' );
    };
    
    var rabbit = new Rabbit('Rabbit');
    
    rabbit.name(); // Error, but it must display "Rabbit"
    rabbit.run(); // works fine
    rabbit.jump(); // works fine

Answer №1

.name is not a function, it actually gets assigned the argument string within the constructor. This property that belongs to the object itself hides the inherited method. If you try to call the string as a function, an error will occur.

To fix this issue, update the code like this:

Animal.prototype.setName = function(name) {
  this.name = name;
  console.log( 'Rabbit name ' + this.name );
};

…

console.log(rabbit.name); // prints out "Rabbit"
rabbit.setName("Roger"); // prints out "Rabbit name Roger"

Answer №2

In your code, there is a conflict between the object field "name" and the function "name". The field is currently overriding the function.

The solution is quite straightforward - rename either the field or the 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

Sending an Angular scope variable to JavaScript

I am working with an angular scope variable that is being used in ng-repeat. My goal is to create a chart that starts from a specific date, ends at another date, and includes a marker for the current day. I am utilizing loader.js for drawing the charts in ...

Easily update form elements with dynamic MySQL integration

I am currently working on creating a page that allows users to add and delete "soldiers" dynamically. Here is the structure I am aiming for: [Text-box][Delete] [Text-box][Delete] [Add-Soldier] It is important to me that this functionality supports MySQL ...

Adding event listeners to elements created dynamically

I am facing an issue with some dynamically generated divs from a JavaScript plugin. The divs have a class .someclass which wraps existing divs. My goal is to add a class to the children of .someclass. I attempted to achieve this by using the following code ...

Is there a way to extract the numerical value from a string within an ID of a div and transform the rest of the string into a variable?

Looking to extract the final id of a div and convert it to a variable. <div class="margin_bot" id="itemRows2"> <p id="rowNum1">...</p> <p id="rowNum2">...</p> <p id="rowNum3">...</p> <p id="rowNum4"> ...

Avoid reloading the page when the form is submitted using form.trigger('submit') command

My current code functions properly when the user clicks on the form's submit button: // load dashboards when filter form is submitted $('div.active form.filter-form').submit(function (e) { // get subm ...

A Guide to Effectively Extracting Data from Second Level JSON Arrays with

Hi, I'm having difficulty fetching the two attributes under CategoryImage in the second level of the JSON array parsing. Can someone help me with this? Thank you. <script> $(document).ready(function() { var cat=""; ...

Indicator count for multiple slick carousels

Is there a way to create individual slide counters for multiple sliders that do not work together? In my current example, the slide counters are functioning together: https://codepen.io/anon/pen/oqqYjB?editors=1010 <div class="container"> <div ...

Ajax request in Rails not receiving a response from the controller

After troubleshooting a simple GET request to the controller action, I confirmed that the request is being made successfully and there are no issues with the controller executing the action. However, I am not receiving any response data. $.ajax({ url: ...

Encountering an Invariant Violation: React does not allow objects to be used as children

I can't figure out why my code isn't working. Every time I run it, I get the error message: Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of chil ...

How can we enhance the backbone sync feature by appending a query string to the URL?

I am facing an issue with adding a token to the backbone URL query string and I am seeking assistance from you all. Here are three important things to note: There is a REST API that requires a token for each request An NGINX backend handles authenticatio ...

Offering substitute text for directly copying and pasting

I remember doing something similar in the past, but I can't seem to find any information about it now. It's proving to be quite difficult to research this particular issue. What I want to achieve is showing one version (A) of text on the screen, ...

Deleting an element from a reference array in Mongoose

In my code, I have a User model that contains an array of references to other users: friends : [ { type: Schema.Types.ObjectId, ref: 'User' } ] I am currently struggling with removing an item from this list. Here is what I have attempt ...

Is there a way to keep a section of an animated class in place?

My website features an animated retractable menu bar with two separate menus. Clicking on one icon activates a sliding motion to reveal that particular menu while causing the second menu to retract in a similar fashion. To achieve a smooth transition effec ...

Creating easy nested list views in React Native using object data structures

I am working with an array of objects that contains user data like this: const userList = [ { "firstName": "John", "lastName": "Doe", "date": "19 March 2018" }, { "firstName": "Anna", ...

Using jQuery to create an array variable and Passing the array to a different PHP page

Although I have managed to create a function that works perfectly for me, I am facing an issue with the jQuery part at the bottom. Currently, I am only able to trigger an alert message and not store the data as a real variable. The function is functionin ...

Which is better for cycling through a list of items: CSS or JavaScript?

Currently, I have a navigation bar set up as an unordered list (<ul>), but some list items are not visible. I want to implement functionality where clicking arrows will move the elements left or right by hiding or showing the leftmost or rightmost it ...

Tips for transferring a calculated value from a child component to a parent component in ReactJs

In my current project, I am faced with the challenge of passing a calculated value from a child component back to its parent. The child component is designed to utilize various user inputs to compute a single value that needs to be returned to the parent. ...

Infura makes ten calls to eth_getBlockByNumber for every eth_call request

Currently, I am in the process of creating a straightforward nextjs API route (https://nextjs.org/docs/api-routes/introduction) that is linked to the Ethereum blockchain for executing a view function (which doesn't require any gas) from a smart contra ...

Is there a way to confirm when all 3 html pages (panes) have been completely refreshed?

I have a webpage with 4 panes, each implemented as separate HTML pages. The last pane needs to perform an action when the previous 3 panes are refreshed. For instance, while the first 3 panes are refreshing, the last pane should display a "LOADING" message ...

Removing an entry from the list using Apollo GraphQL's Optimistic UI Mutation

I'm in search of a solution to implement an optimistic UI feature for deleting an item from a list. The query used for the list is: myQuery{ Foo:{ Bar:{ id } } Delete mutation: mutation deleteBar(input: barInput!){ deleteBarItem: (respon ...