0

I am trying reference the parent object. This works fine in normal functions/methods, but in the closure/ self-invoking function, the parent object is undefined. How does the scoping work in this case? How can we reference the parent obj?

var user = {
        name: "Some user",
        methods: {
            getUserName: function() {
                    return user.name

                 },
            GetUserName: function() { }
        }
        f_name: (function () {
               var fname = user.name; // **Error: user is undefined**
               fname = fname.split(" ")[0];
               console.log(fname); 
               return fname
        }())
    }
user.methods.getUserName(); // "Some user"
user.f_name // should log "Some" to the console;
kennsorr
  • 292
  • 3
  • 20
  • 1
    The problem is simply that the IIFE is executed immediately, which is before `user` has finished being defined. You could make this work (depending on the precise intent) by not executing the function (`fname` simply holding the function) and then accessing `user.f_name()`. – Robin Zigmond May 05 '20 at 21:02
  • 2
    The problem is not with scoping. The problem is with evaluation order: when the value for the `f_name` property of the object literal is computed, `user` is not yet assigned. – Bergi May 05 '20 at 21:02
  • Thanks, I didn’t think the IIFE would execute before the parent object containing it had been set. Weird. I solved this by using a getter function. Thanks! – kennsorr May 06 '20 at 18:19

0 Answers0