0

I have a web page and I would like to attach some custom properties to the global window-object. I noticed when debugging the code that my console outputs the property I have assigned to the window object before it is actually assigned. The execution order goes as follows:

console.log(window); //Outputs window object with "myApp"-property with the value "something"
console.log(window.myApp); //Outputs "undefined"

window.myApp = "something";

console.log(window.myApp); //Outputs "something"
console.log(window); //Outputs window object with "myApp"-property with the value "something"

I cannot reproduce this behaviour with normal Javascript objects. For example:

var obj1 = {a: "bar"};

console.log(obj1); //Outputs Object {a: "bar"}. does NOT output obj1.b

obj1.b = "foo";

console.log(obj1); //Outputs Object {a: "bar", b: "foo"}

What is the logic behind this?

vivask
  • 32
  • 2
  • 4
  • If you click on the `Object { a: "bar" }` you'll see both `a` and `b` properties. It happens, because the console converts the object into a String to show some of its contents, and then does that again after you insert another property. But, as soon as an Object in Javascript is a reference, in fact the Object has both `a` and `b`, when you try to see its live properties. When you log the `window` object into the console, the console also converts it to a string, but not to show its properties, so, you'll only see them after clicking, and then getting the same behavior as clicking the Object. – Buzinas Nov 01 '15 at 10:38
  • If you want to see the properties at the time you're logging them into the console, then you could use `JSON.stringify(window)` and `JSON.stringify(obj1)`, and then, you will see that the first time you log `window`, you won't see any `myApp` property into it. – Buzinas Nov 01 '15 at 10:39

0 Answers0