1

I have an object which is declared as following (it has as value a global variable):

var example = {
    "foo": window.bar
} 

Steps after other method is executed and this value change, but if I want to use the value in the object, this is undefined.

The listeners seem to be exclusively to DOM elements but not to values, There is a way to bind the value at the object to a variable or something that update the value in the object?

here a example what I want to achieve: https://jsfiddle.net/ptbqqk6o/2

Thanks in advance

Jose Rojas
  • 3,490
  • 3
  • 26
  • 40

2 Answers2

2

example.foo is undefined as soon as you execute the assignment to example: the value of window.bar is resolved at that very moment, which does not yet exist in your case, ... so undefined.

If you want to maintain a reference to an object that can mutate in the future, then define window.bar first, before the assignment to example, and define it as an object. Then, never reassign a value to window.bar, but only mutate it: that way the reference will remain shared:

window.bar = {}; // An object, for later mutation.

var obj = {
    foo: window.bar // a reference to the above object
}

window.bar.message = "this works!";

console.log(obj.foo);
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Thank you, I just edited my question with your suggestion. Where can I find further information about mutator and how this works? – Jose Rojas Aug 01 '17 at 18:28
  • 1
    I would advise to read about JavaScript's way of passing arguments: [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language). It is not exactly the same subject, but I think if you understand that, you'll see the light on what happens when you assign a new value to a variable as opposed to what happens if you *mutate* it, i.e. you change a property value of the variable's (object) value, but don't change the variable via direct assignment. – trincot Aug 01 '17 at 20:14
0

In the code in your fiddle:

var json = {
    foo : window.bar
}

window.some = 'bar';

alert(json.foo);

When you construct the jsonExample object, the value of window.bar has not yet been set. Thus jsonExample.foo is set to undefined. Try this:

window.bar = 'bar';

var json = {
    foo : window.bar
}

alert(json.foo);
McHat
  • 830
  • 5
  • 15