2015-10-17 98 views
0

我有以下代码。现在,当构造函数被调用时,对象被创建。现在,在更新字段时,他们正在像这样更新。请注意,我无法修改Comment(),因为它是由猫鼬创建的。Javascript中的对象声明

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

回答

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

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

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类,所以如果你的目的是保持组织,那么这是一种合理的方法,以保持自弄乱你的构造方法