Access properties in sub object in javascript -


this question has answer here:

i wrote simple test script in fiddle: http://jsfiddle.net/resting/qfcue/

what i'm trying set margin property 2, , let obj.foptions.labelmargin , obj.marginclone take in value.

i know possible change in value in obj.foptions.labelmargin , obj.marginclone directly. wouldn't allow me "change 1 place, change in places".

instead, both obj.foptions.labelmargin , obj.marginclone undefined.
how this.margin read 2?

code:

var obj= {     margin: 10,     setmargin: function(val) { this.margin = val; },     foptions: { labelmargin: this.margin },     marginclone: this.margin }  obj.setmargin(2); console.dir(obj.foptions); console.log(obj.marginclone); console.log(obj.margin); 

the typical way in javascript use function create scope holds state. here's code rewritten in style:

function obj() {     var = this;      that.margin = 10;     that.setmargin = function(val) {          that.margin = val;      };     that.foptions = {          labelmargin: that.margin      };     that.marginclone = that.margin; }  var inst = new obj(); inst.setmargin(2); console.dir(inst.foptions); console.log(inst.marginclone); console.log(inst.margin); 

see on jsfiddle.

with respect marginclone, recall javascript has reference semantics object types--so scalar values, you'll making copy. can wrap scalar in object if want pass-by-reference.


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -