Saturday, 15 August 2015

Can someone explain this small piece of javascript code to me? -



Can someone explain this small piece of javascript code to me? -

basically expect console.log output 'yeah' doesn't. can create output yeah without straight referencing within of usefulfunction?

app = { config: { updatethis: 'false' }, init: function(){ this.usefulfunction(this.config.updatethis); this.consoleit(); }, usefulfunction: function(item){ item = 'yeah'; // swap above line line below , works expected // this.config.updatethis = 'yeah'; }, consoleit: function(){ console.log(this.config.updatethis); } } app.init();

in usefulfunction, expecting c++ style of pass reference impact original reference config.updatethis, however, when call

this.usefulfunction(this.config.updatethis);

you creating new reference 'false' string (to pass usefulfunction), , can't update original reference in this.config usefulfunction.

the way address pass name of object update. again, there no c++ pass reference in js. working example

app = { config: { updatethis: 'false' }, init: function(){ this.usefulfunction(this.config, 'updatethis'); this.consoleit(); }, usefulfunction: function(object, prop){ object[prop] = 'yeah'; }, consoleit: function(){ console.log(this.config.updatethis); } } the problem not strings immutable

áš—̸̢̛͝ claims problem strings immutable; however, problem deeper that. fact strings immutable means can't alter current reference (and hence have other references update), if mutable, couldn't set separate reference , impact existing references

var = {b:1}; function change(obj) { // assigning {c:2} obj not // obj , both point same object, // next statement simple create obj point different object // in other languages, define function(&obj) {} // allow next statement intended obj = {c:2}; } change(a); console.log(a); // still {b:1}

javascript

No comments:

Post a Comment