简体   繁体   English

JS将属性添加到对象

[英]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. 当我在client.name中执行client.name的控制台日志时,它返回undefined。 Can someone point me out what I'm doing wrong ? 有人能指出我做错了吗? I'm new to JS. 我是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) 也许尝试制作一个片段给出相同的错误(你可能会自己绊倒解决方案)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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