Javascript中的对象声明
Object declaration in Javascript
我有以下代码。现在当构造函数被调用时,对象就被创建了。现在,当更新字段时,它们是这样更新的。注意,我不能修改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();
};
你不能安全地改变注释类,所以如果你的意图是保持组织,那么这是一个合理的方法来防止混乱你的构造方法
相关文章:
- 使用同一对象中的其他变量声明变量
- 如何在AngularJS工厂中正确声明对象属性
- 在JS中用引号声明对象和数组是否更快
- 什么'It是声明对象的最佳方式
- Javascript OOP - 声明对象的方法
- 在 JavaScript 中,在声明对象的新键:值对时,引用对象的变量名与使用“this”之间是否存在差异
- 声明对象超出范围
- 声明对象的两个语句之间的差异
- 在使用 Gulp 在 javascript 中声明对象时,在 Git bash 中出现以下错误“语法错误:意外标识符”
- 在处理.js中,如何声明对象类型和对象数组
- 声明对象并返回它的函数
- 数组中声明对象的函数未定义--NO!不是
- 函数调用以在JavaScript中声明对象属性
- 声明对象以在单个函数中重复使用的范围
- 丢失的在声明对象变量之前
- 不声明对象数组的Ng-repeat
- 应该在javascript中声明对象属性吗?
- 在nodejs/commonjs模块的根作用域中声明对象——用var还是不用var
- 在声明对象时访问属性
- 除了以下方式之外,是否有其他方法可以在 Javascript 中声明对象