Uncovering the Secrets of JavaScript Prototypes

Currently diving into the world of JavaScript prototypes, I stumbled upon an issue.

<script type="text/javascript>
        function Person(){}
        Person.prototype.name="aa";
        Person.prototype.sayName=function(){
            alert(this.name);
        }
        var person1=new Person();
        person1.name="bb";
        alert(person1.sayName());
    </script>

Can anyone explain why it is displaying both "bb" and undefined as results?

Answer №1

When you create an object of type person and set the name property as "bb", it causes confusion because in the function you attempt to alert the sayname which is not a property, but rather a function.

Here's a more detailed explanation: Essentially, the function defined here serves as a factory for creating objects with specific properties and methods.

function Person(){}
        Person.prototype.name="aa";
        Person.prototype.sayName=function(){
            alert(this.name);
        }

After defining the function, you proceed to create an instance of this object type using the following code:

var per = new Person();

You have the ability to overwrite the default property or call the method using the instance `per` like so:

per.name = "bb";

The above code changes the property name to "bb". Therefore, when calling the sayName method, it will output "bb" as expected:

per.sayName();

When the sayName function is executed, the alert displays "bb" because 'this' refers to the current object instance, and then retrieves the value of the property.name

Answer №2

Forget about the prototype and properties, everything is running smoothly as planned. The issue lies in person1.sayName() not returning anything, causing it to implicitly return undefined, which will be displayed by the alert(…).

If you only want one alert, you can either:

Person.prototype.sayName = function() {
    return this.name;
};
…
alert(person1.sayName());

or

Person.prototype.sayName = function() {
    alert(this.name);
};
…
person1.sayName();

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

Engaging with the CSS content attribute

Below is a code snippet that inserts an image before the header tag. Is there a way to incorporate JavaScript or jQuery in order to execute certain actions when the inserted image is clicked? h1::before { content: url(smiley.gif); } The HTML code fo ...

What causes delays in the calculation of element heights and widths by jQuery's height() and width() methods?

Recently, I've encountered a performance issue with jQuery's height() and width() methods taking too long to calculate an element's height and width. How can I optimize these methods for Internet Explorer 8+, as well as the latest versions o ...

React component tirelessly retrieving and refreshing data without purpose

Currently, I have a react component that fetches data continuously for visualization purposes. This constant fetching is unnecessary and I am looking for a way to optimize it. The structure of my component is as follows: export default function Analytics( ...

Adjust the horizontal position of the background by +/- X pixels

Is there a way to adjust the background-position by a specific distance, say 20px, from its original position? For example: $(".selector").animate("slow").css("backgroundPosition", "center -=20px"); (Unfortunately, this approach doesn't yield the d ...

Angular 2 Error: Unresolved Promise rejection - Unable to assign value to reference or variable

I'm currently working on an Ionic 2 app that includes a barcode reader feature. However, I encountered the following issue while trying to display data: Unhandled Promise rejection: Cannot assign to a reference or variable! ; Zone: ; Task: Promi ...

Contrasting $(document).ready and directly writing jQuery statements at the beginning of a script

What distinguishes coding with and without $(document).ready? Consider the following: $(document).ready(function() { $("#button").click(function() { //Code }); }); Versus: $("#button").click(function() { //Code }); Also : <inp ...

I would like for my element to increase and decrease in size while rotating when the button is clicked

I am trying to create an element that changes its size while spinning when a button is clicked. It seems to be working fine on hover, but not onclick. Here is the code I have: <div class="rec">Rec</div> <button id="button&quo ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

Upon successful saving, the values stored in Ionic Storage remain unchanged and do not automatically update in Capacitor/Ionic 6

Utilizing the Ionic storage plugin, I am able to store and retrieve values in my app. The settings page allows users to make selections that impact the overall app experience. This is the code snippet from my settings.page.html <ion-header> <io ...

What could be the reason why window scrolling is not triggering with Jquery?

Trying to set image source when scrolling down has been a challenge. I previously asked this question, and while the suggested answer seems right, I am still facing issues. Even after attempting to use an alert on window.scroll, no alerts were triggered. ...

The JavaScript code is failing to load

Ensuring my HTML and JavaScript code is well-organized, I have separated all the JavaScript code into different files. However, when attempting to insert the code into the HTML page, it does not function as expected: <html xmlns="http://www.w3.org/199 ...

Reactjs implemented with Material UI and redux form framework, featuring a password toggle functionality without relying on hooks

Currently, I am working on a react project where I have developed a form framework that wraps Material-UI around Redux Form. If you want to check out the sandbox for this project, you can find it here: https://codesandbox.io/s/romantic-pasteur-nmw92 For ...

What is the best way to adjust the screen to display the toggle element when it is opened?

Here is the code I'm currently using to create a toggle button that shows or hides extra content when clicked: $(".toggle .button").click(function() { $(this).next().slideToggle('fast'); }); The issue I am encountering is that if t ...

Utilizing the dynamic flair with React's map functionality

In my display area, which is a div element, I have rendered some text using spans. I utilized the map function to render the text from an array. The issue arises when I apply a color class to the span elements within the map function, causing all text to ...

SonarQube flagging a suggestion to "eliminate this unnecessary assignment to a local variable"

Why am I encountering an error with SonarQube? How can I resolve it since the rule page does not offer a specific solution? The suggestion is to eliminate the unnecessary assignment to the local variable "validateAddressRequest". validateAddress() { ...

I am facing an issue where this loop is terminating after finding just one match. How can I modify it to return

I am currently working with an array that compares two arrays and identifies matches. The issue is that it only identifies one match before completing the process. I would like it to identify all matches instead. Can anyone explain why this is happening? ...

Assign value to twig variable using JavaScript in Symfony version 3.4

Hello everyone, I am currently working on a form that is functioning well. However, I am facing an issue with setting the localization of a place manually using latitude and longitude values. To address this, I decided to create a map with a draggable mark ...

Steps to display text in a div upon clicking on an image

I am trying to create an image with two DIVs separated by a black line. The left DIV will contain 4 images, and I want the following functionality: When a user clicks on any of the buttons in the left DIV, a corresponding text should be revealed in the ri ...

javascript function not being invoked

Currently, I have incorporated the following HTML <html> <head> <Title>EBAY Search</title> </head> <script language="JavaScript" src="ajaxlib.js"></script> <body> Click here & ...

Is it possible to generate a star rating system from an image using a decimal value?

Recently, I have been eager to convert a number into a star rating and stumbled upon this helpful post here: . The post perfectly explains what I am looking to achieve. Despite following the instructions provided, I am facing difficulties getting it to fun ...