Javascript中的对象声明

时间:2015-10-17 05:40:54

标签: javascript node.js

我有以下代码。现在,当调用构造函数时,将创建对象。现在,在更新字段时,它们会像这样更新。请注意,我无法修改Comment(),因为它是由mongoose创建的。

  var newComment = new Comment();
  newComment.content = req.body.content;
  newComment.user.id = req.body.id;
  newComment.user.name = req.body.name;
  newComment.user.profilePicture = req.user.profilePicture;
  newComment.votes.up = [];
  newComment.votes.down = [];
  newComment.comments = [];
  newComment.timestamp = Date.now();

有没有办法像这样更新对象:

newComment.SOMEFUNCTION({
  content = req.body.content;
  user.id = req.body.id;
  user.name = req.body.name;
  user.profilePicture = req.user.profilePicture;
  votes.up = [];
  votes.down = [];
  comments = [];
  timestamp = Date.now();
});

2 个答案:

答案 0 :(得分:3)

Object.assign

  

Object.assign()方法用于将所有可枚举的自有属性的值从一个或多个源对象复制到目标对象。

Object.assign( newComment, {
    content : req.body.content,
    user : {
      id : req.body.id,
      name : req.body.name,
      profilePicture : req.user.profilePicture
    },
  votes.up : [],
  votes.down : [],
  comments : [],
  timestamp : Date.now()
});

http://jsfiddle.net/r8pavnuv/

答案 1 :(得分:1)

这样做的原因是什么?它仅用于组织目的吗?如果是这样,那么是什么阻止你做一个单独的功能:

var newFunc = function(newComment){
  newComment.content = req.body.content;
  newComment.user.id = req.body.id;
  newComment.user.name = req.body.name;
  newComment.user.profilePicture = req.user.profilePicture;
  newComment.votes.up = [];
  newComment.votes.down = [];
  newComment.comments = [];
  newComment.timestamp = Date.now();
};

您无法安全地更改Comment类,因此如果您的目的是维护组织,那么这是一种合理的方法,可以避免使构造函数方法混乱