Why does the getter consistently generate the previous value?

Check out this code snippet:

function User(fullName) {
    this.fullName = fullName;
    Object.defineProperties(this,
        {
            firstName: {
                get: function () {
                    return fullName.split(" ")[0];
                }
                ,
                set: function (fName) {
                    this.fullName = fName + " " + this.lastName;
                }
            },
            lastName: {
                get: function () {
                    return fullName.split(" ")[1];
                }
                ,
                set: function (lName) {
                    this.fullName = this.firstName + " " + lName;
                }
            }
        })

}

Let's execute the following code as well:

var vasya = new User("oldName oldSurname");

console.log(vasya.firstName); // 

vasya.firstName = "newName";
vasya.lastName = "newSurname"

console.log(vasya.fullName);

The output should be newName OldSurname

If you modify the code slightly like this:

var vasya = new User("oldName oldSurname");

console.log(vasya.firstName); //
console.log(vasya.lastName); //

vasya.firstName = "newName";
vasya.lastName = "newSurname"

console.log(vasya.fullName);

You might see oldName newSurname

Can you figure out why you are getting oldName instead of newName?

Answer №1

After some experimentation, I discovered that there was a naming conflict in the code. The revised version below functions correctly:

function User(fullNameValue) {
    this.fullName = fullNameValue; // changed function argument name
    Object.defineProperties(this,
        {
            firstName: {
                get: function () {
                    return this.fullName.split(" ")[0];//Modified to utilize "this" keyword
                }
                ,
                set: function (fName) {
                    this.fullName = fName + " " + this.lastName; 
                }
            },
            lastName: {
                get: function () {
                    return this.fullName.split(" ")[1];//Adjusted to use "this"
                }
                ,
                set: function (lName) {
                    this.fullName = this.firstName + " " + lName;
                }
            }
        })

}

Answer №2

Ensure to utilize the "this" keyword when accessing fullNameValue; otherwise, it will use the variable that was passed as a parameter.

function User(fullName) {
    this.fullName = fullName;
    Object.defineProperties(this,
    {
        firstName: {
            get: function () {
                return this.fullName.split(" ")[0];
            }
            ,
            set: function (fName) {
                this.fullName = fName + " " + this.lastName;
            }
        },
        lastName: {
            get: function () {
                return this.fullName.split(" ")[1];
            }
            ,
            set: function (lName) {
                this.fullName = this.firstName + " " + lName;
            }
        }
    })

}

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

React i18next provides a fallback language in case the specified language is not

In my React app, I have implemented i18next for translating files, using the following approach: i18next.js (original) import i18next from 'i18next'; import XHR from 'i18next-xhr-backend'; import detector from 'i18next-browser-lan ...

Tips for managing the onloadedmetadata event

If a video file cannot be played by the browser due to format or codec issues, I want to notify the user about it. When the browser is unable to play a video (because of unsupported format or codec), the onloadedmetadata event does not occur. I have some ...

Exploring ways to retrieve item metadata from a Stripe checkout session

When setting up a Checkout session, I dynamically create prices using the price_data and product_data properties. I include metadata for each item within the product_data.metadata property. However, after a successful payment is made, I retrieve the sessi ...

Outputting messages to a component with React

I'm attempting to create a component similar to a console where messages are displayed one after the other instead of replacing the old message. My goal is to have a component where I can input strings, like in a chatbox, using different parts of my ...

Utilize jQuery to extract data from a JSON object

While I have come across numerous examples of parsing JSON objects in jQuery using $.parseJSON and have grasped the concept, there are some fundamental aspects missing that are preventing me from successfully parsing the following VALID JSON: { "studen ...

I need help getting my Vue.JS project to function properly when it is deployed on a server

After creating a new VueJS project using the Vue UI, I noticed that everything runs smoothly locally at http://localhost:8080/ with no errors. However, when I build the project and upload the files from the dist folder to my hosting package via FTP, I end ...

Using the methods res.render() and res.redirect() in Express.js

I'm facing a challenge with a route in my express app, where I need to achieve the following: Retrieve data from an external source (successful) Show an HTML page with socket.io listening for messages (successful) Conduct lengthy calculations Send a ...

Combine JavaScript array objects based on their unique IDs

Looking to combine 2 arrays of objects based on IDs (ID and AUTOMOBIL). However, the current code only saves the last array of objects (OPREMA). Any suggestions on how to merge all of them correctly? If the ID in a1 is == 1, I want to save all OPREMA wher ...

Ways to invoke a controller function from a window listener function

Is there a way to trigger the close function from window.onbeforeunload even when closing the app through 'right click' -> 'close window'? It seems that this.close() is not working in this scenario, possibly due to scope issues. The ...

RequestDispatcher.forward() does not work when servlet is invoked through an Ajax POST request

My login page involves user authentication through the firebase and sending the request to a servlet. When I click the submit button with correct credentials, the firebase authentication works, the servlet is called but an error is displayed in the browser ...

What are some ways I can optimize my Bootstrap CSS code to enhance responsiveness across different page widths?

After creating this fiddle, I noticed that my webpage layout with two texts stacked on top of each other looks great on wide screens. However, when the screen size is reduced or viewed on a mobile device, the layout gets all messed up. Take a look at this ...

Ways to create dynamic functionality with JavaScript

I need to iterate through the document.getElementById("b") checked in a loop. Is this achievable? How can I implement it? <img class="img-responsive pic" id="picture" src="images/step1.png"> <?php //get rows query ...

Angular not recognizing draggable true functionality

I am encountering an issue with a div element: <div draggable = "true" ng-show="showPullDown" class="topPull stretch" draggable > </div> The draggable=true attribute is not functioning as expected. I have attempted to set it through the co ...

Similar to Jquery ajax, Titanium also offers a powerful tool

Currently, I have been making an API call using Titanium in the following way: var url = "http://www.appcelerator.com"; var client = Ti.Network.createHTTPClient({ // callback when data is received onload : function(e) { Ti.API.info("Re ...

Modify the css of the initial div following a live click

After clicking on the span.submit-comment, I am looking to modify the CSS of a specific div. Can anyone advise me on how to achieve this? I attempted to change the background color of the div in the success section of the script like so: $('div.new ...

Difficulty sending a parameter to the onClick function of a React Button

I'm struggling with passing parameters to my callback function when clicking a material-ui button. Unfortunately, the following approach is not yielding the expected results. const fetchData = async (param) => { } <Button onClick={fetchData(&a ...

Utilizing VueJs (Quasar) to access vuex store within the router

Recently, I have been diving into learning Vuex and creating an authentication module. Following a tutorial, I reached a point where I needed to use the store in the router. However, after importing my store at the top of the router index.js file, I notice ...

Can a single volume control be used to manage the audio of multiple sources at once?

I am currently working on a project for my personal interactive video website. I am trying to figure out how to create one volume control that can adjust the audio for multiple tracks at once. Can anyone help me with this? So far, I have successfully crea ...

Create node panels using GoJS and apply paint to them to enhance

Hey there! I'm looking to style my node similar to the one on the right using GOjs. Any suggestions on how I can achieve that? The left node is what I currently have, but I really want to paint it like the right node. It seems like some parts are mi ...

An easy way to place text along the border of an input field in a React JS application using CSS

I am struggling to figure out how to create an input box with text on the border like the one shown in the image below using CSS. I have searched extensively but have not been able to find any solutions to achieve this effect. I attempted using <input&g ...