Javascript中的对象声明

Object declaration in Javascript

本文关键字:声明 对象 Javascript      更新时间:2023-09-26

我有以下代码。现在当构造函数被调用时,对象就被创建了。现在,当更新字段时,它们是这样更新的。注意,我不能修改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();
});

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/

这样做的原因是什么?只是为了组织的目的吗?如果是这样,那么是什么阻止你创建一个单独的函数呢?

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();
};

你不能安全地改变注释类,所以如果你的意图是保持组织,那么这是一个合理的方法来防止混乱你的构造方法