1

In the code below, why does console.log(myObject.obj1 ) display a proto object in the console instead of actual object data? Meanwhile, I can see the obj1 data using console.log(myObject).

$(function () {

    var myObject = {
        obj1: {},
    }

    $.ajax({
        url: "foobar.json",
        success: function (data) {
            myObject.obj1 = data.obj1;
        }
   });

    console.log(myObject); // displays myObject data in console!
    console.log(myObject.obj1 ) // displays a __proto__ object :(

});

If this is related to async code, why does console.log(myObject) work? Maybe this is related to scope, i.e. myObject.obj1 being out of scope?

Sébastien
  • 11,860
  • 11
  • 58
  • 78
  • Exactly, success handler will be called after the request is fulfilled. question: what do you get when you ```console.log(data)``` inside the success handler? like so: ```success: function (data) { console.log(data); };``` – Varinder Feb 04 '18 at 19:57
  • Can you post the exact console.log() statements output? – CodeAt30 Feb 04 '18 at 19:57
  • `If this is related to async code`, There is no if here, it's async code. `myObject.obj1 being out of scope?` No, it's in scope, it's an async problem. – Keith Feb 04 '18 at 19:57
  • console.log(data) outputs full data from the json file as several objects. – Stefan Dahl Feb 04 '18 at 20:00
  • However, if i print console.log(myObject.obj1 ) i get: {} __proto__ : constructor : ƒ Object() hasOwnProperty : ƒ hasOwnProperty() isPrototypeOf : ƒ isPrototypeOf() propertyIsEnumerable : ƒ propertyIsEnumerable() toLocaleString : ƒ toLocaleString() toString : ƒ toString() valueOf : ƒ valueOf() __defineGetter__ : ƒ __defineGetter__() __defineSetter__ : ƒ __defineSetter__() __lookupGetter__ : ƒ __lookupGetter__() __lookupSetter__ : ƒ __lookupSetter__() get __proto__ : ƒ __proto__() set __proto__ : ƒ __proto__() – Stefan Dahl Feb 04 '18 at 20:01
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Feb 04 '18 at 20:02
  • It will work when you view it in console, as the console has captured the scope of myObject, so when the aJax call is finished you will see the result. It's just the result updates that fast you don't see it's been done async. By the time you click that plus to expand in the console window, you Ajax call has likely finished. – Keith Feb 04 '18 at 20:04
  • i still dont see the solution to my problem in those links because i cant access myObject.obj1 in the rest of the code. – Stefan Dahl Feb 04 '18 at 20:07

0 Answers0