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

Chunk loading in IE 11 has encountered an error

Having an issue with my website which is created using Angular 5. It seems to be malfunctioning in IE 11, and I am encountering the following error in the console: https://i.stack.imgur.com/Ek895.png Any insights on why my Angular code isn't functio ...

Information is inaccessible beyond onBeforeMount in the Composition API of Vue 3

In my code snippet block, I have the following code: <script setup lang="ts"> import ApiService from '../service/api' import { reactive, onBeforeMount } from 'vue' let pokemons = reactive([]) onBeforeMount(async ()=> ...

Is it possible to override values set in the constructor(props) in React? If not, what is the best way to set defaults that can be overwritten later?

I'm confident I know the solution to this problem because my setState({}) seems to have no effect. This is the constructor code that I currently have: constructor(props) { super(props); this.state = { percentiles: { incN ...

Tips for extracting CSS data with Selenium webdriver's executescript function

Just starting to learn Javascript in a Node environment... I'm trying to use the code snippet below to extract CSS values for a specific web element, but I'm having trouble parsing it in JavaScript. driver.executeScript(script, ele).then(p ...

javascript implement a process to iteratively submit a form using ajax

I have a dynamic form with an unknown number of input fields that are not fixed. While searching for solutions, I came across jQuery ajax form submission which requires manually constructing the query string. In this scenario, the number of input fields ...

Ajax fails to transmit data to PHP script

Having encountered an issue with my script that prevents sending data from AJAX to a PHP file, I decided to debug it by logging the form data before running it through the AJAX function. The data obtained was as follows: Form: name=jim&email=info%40te ...

Mongoose and Next.js: Encountered Runtime Error - Cannot Access Undefined Properties (Token)

For some reason, the Model I defined is not working properly, despite being similar to another one that works without errors. Can anyone help me figure out why? If you need to see a minimal, reproducible example, check it out here. The problematic code: ...

What could be causing my input to not activate my function?

I am having issues with my input buttons not triggering my functions. Can anyone provide some insight into this problem? <div id="windowBar"> <h3>Imagine you were a superhero...</h3> <input id="WindowClose" type="button" onclick=" ...

Ways to identify if a resize event was caused by the soft keyboard in a mobile browser

Many have debated the soft keyboard, but I am still searching for a suitable solution to my issue. I currently have a resize function like: $(window).resize(function() { ///do stuff }); My goal is to execute the 'stuff' in that function on ...

Mongodb/mongoose encountering issues with saving data only once, resulting in a 500 error

When I send json to my node.js/express app, it successfully receives the data and performs the desired action, but only once. After starting the appjs for the first time, it returns a 200 response code and saves the data to my mongodb. However, any subsequ ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

What is the reason behind ASP MVC model binder's preference for JSON in POST requests?

Is there a way to bind data to a model when sending a 'GET' request with JSON.stringify() using AJAX? Currently, the model value is always null when using 'GET', but it works fine with 'POST'. Are there any solutions for this ...

Browsing through tabs to locate specific text

Currently, I am developing a feature for a Chrome extension and I could use some assistance in debugging. The feature involves retrieving a user's input as a string from a text box on popup.html and then scanning through all the open tabs in the curr ...

The continuation of unraveling the mystery of utilizing `overflow-y:scroll` in a horizontal slider

As a beginner, I realized too late that adding code in comments is not an option. Consequently, I decided to create a new question and ask for your assistance once again. To optimize the use of space, I have implemented bxSlider with fixed dimensions (wid ...

Sending a JSON object with scheduled task cron job

I have a PHP cron job that is quite complex. It retrieves data from an external webpage and consolidates all the information into one variable, encoding it in JSON. Unfortunately, this entire process is slow and consumes a significant amount of time. My d ...

Using jQuery JSONP only functions with URLs from the same site

I am looking to send a request to an API that returns data in json format. The API is located on a sub-domain of the domain where my script will be running (although currently it's on a completely different domain for development, localhost). My unde ...

Switch the script: convert from jQuery to traditional JavaScript code

I've been trying to transition from using jQuery for a toggle script on my website to just using normal JavaScript in order to clean up the code. However, I'm having trouble converting the existing jQuery code into vanilla JavaScript. Here is th ...

Issues with concealing the side menu bar in Vue.js

I've been attempting to conceal the side menu bar, with the exception of the hamburger icon when in the "expanded" state. Despite my efforts to modify the CSS code, I am still struggling to hide the small side menu bar. The following images represent ...

What is the reason behind my button appearing beneath my links in React?

Here is an image showcasing the current header render. The header consists of a HeaderMenu and 3 Links. While the links are functioning properly, the HeaderMenu is causing the links to be positioned below it. The HeaderMenu includes a div that wraps a Butt ...

Designing a dropdown menu within displaytag

I am currently utilizing displaytag to present tabular data, but I aspire to design a user interface akin to "kayak.com" where clicking on a row reveals additional details without refreshing the page. Here is an example scenario before clicking the Detail ...