在这个Express路由中,我导入了这个透视图模块。
//routes/api.js
var perspectives = require('../controllers/perspectives');
router.route('/perspectives/newsletter')
.post(function(req, res){
var p = perspectives.setNewsletterHttpRequest(req);
p.updateNewsletter();
});setNewsletterHttpRequest(req)方法接受请求对象,然后返回透视图模块本身的副本(Object.assign)。
//controllers/perspectives.js
perspectives.setNewsletterHttpRequest = function(req, updateMarketoOnly) {
let user = req.body.users[0];
this.validBpNewsletterUpdateInput = true;
this.user = user;
return Object.assign({},this);
}
module.exports = perspectives;通过Object.assign在setNewsletterHttpRequest中返回这个模块是否保持了对象的隔离,以便每个请求都创建自己的透视图对象实例(每个实例都通过http请求req.body.users行设置了自己的用户值)?我试图确保不同的请求没有任何方法来修改同一个对象,但是每个请求都在为自己的实例修改状态。谢谢。
发布于 2017-04-06 16:17:49
Object.assign()将从源对象复制到目标对象,因此在您的示例中,每个对象将与所有其他对象分离。但是..。
如果任何属性值都是对象(例如,数组),则将通过引用复制它们。(这在技术上可能是不正确的,但对于这种情况来说,这已经足够了。)哇哦:
var source = {num:0, str:'', arr:[], obj:{}};
var a = Object.assign({}, source);
var b = Object.assign({}, source);
console.log(a === b); //false
console.log(a == b); //false
// Let's modify `b` and see what happens.
b.added = 'I added this';
console.log(a.added); //undefined, cool
b.num = 4;
console.log(a.num); //0, cool
b.arr.push('new value');
console.log(a.arr) //['new value'], wha??!!!
b.obj.newValue = 'new value';
console.log(a.obj) //{newValue: 'new value'}, also wha???!!!!所以,是的,结果对象是不同的对象,但是要小心,因为它是一个浅浅的副本!
https://stackoverflow.com/questions/43260458
复制相似问题