Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Adding property to object

Tags:

javascript

I'm trying to add a property to an object the following way:

function methodA(client, page){
    Object.defineProperty(client, 'name', {
        value: page,
        writable: true,
        enumerable: true,
        configurable: true
      });

    methodB(client)
}

When I do a console log of client.name in methodB it returns undefined. Can someone point me out what I'm doing wrong ? I'm new to JS.

like image 691
elcharrua Avatar asked Feb 07 '26 02:02

elcharrua


1 Answers

Giving your code some dummy values it seems to work perfectly well. The error must be elsewhere. Run the snippet and see:

function methodA(client, page){
    Object.defineProperty(client, 'name', {
        value: page,
        writable: true,
        enumerable: true,
        configurable: true
      });

    methodB(client)
}

function methodB(client) {
    console.log(client);
    console.log("Name property is: "+client.name);
}

methodA({a:9}, 12);

Maybe try to make a snippet the gives the same error (you might stumble into the solution by yourself in doing so)

like image 180
Michael Beeson Avatar answered Feb 08 '26 14:02

Michael Beeson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!