node.js - Object Assign and object instances -
in express route, import perspectives module.
//routes/api.js var perspectives = require('../controllers/perspectives'); router.route('/perspectives/newsletter') .post(function(req, res){ var p = perspectives.setnewsletterhttprequest(req); p.updatenewsletter(); }); the setnewsletterhttprequest(req) method takes request object , returns copy (object.assign) of perspectives module itself.
//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; does returning module via object.assign in setnewsletterhttprequest keep object isolated each request creates own instance of perspectives object (each own user values set via http request req.body.users[0] line)? i'm trying ensure there isn't way different requests modify same object each request modifying state own instance. thanks.
object.assign() copies source object target object, each object separate others in case. however....
if of property values objects (including, example, arrays), copied reference. (that may not technically correct, it's adequate shorthand situation.) sooooo:
var source = {num:0, str:'', arr:[], obj:{}}; var = object.assign({}, source); var b = object.assign({}, source); console.log(a === b); //false console.log(a == b); //false // let's modify `b` , see 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'}, wha???!!!! so, yes, resulting objects different objects, careful because it's shallow copy!
Comments
Post a Comment