简体   繁体   中英

JS Adding property to object

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM