2015-10-17 147 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類,所以如果你的目的是保持組織,那麼這是一種合理的方法,以保持自弄亂你的構造方法