Here is my test code that I would like to work.
function test() {
var val = 'var ref',
tobj = new testObj(this);
tobj.alertParentVal(); //alert 'var ref'
val = 'new val';
tobj.alertParentVal(); //alert 'new val'
}
function testObj(o) {
this.alertParentVal = function() {
alert(o.val);
}
}
Without passing the values of ‘val’ to the new testObj, how can I reference ‘val’. If this is not possible. Is there a way to keep a reference to the test() functions variable so that if the value changes in the function I can use the new value in the object.
Variables aren’t accessible as properites, except for on the global object.
You’d need to give the object a function that references the variable in order to read it from outside the variable scope…
DEMO: http://jsfiddle.net/a2HfG/1/