0
var a={
   name:"Rhona",
   check:(function(){
          return this.name;
            })();
   }
 console.log(a.check)// This returns ""

An empty string I expected it to return Rhona,it didn't give undefined or null but an empty string whats going on here?

And i also want to know why when I access an objects property which isn't there it gives undefined instead of giving not defined I recognize undefined is the value given to variables at creation phase,execution phase then initializes the value so if there is no initialization it stays undefined so when i access an object property lets say a.lastname which isn't present shouldn't java script return not defined why is it giving undefined instead?

  • Possible duplicate of [Self-references in object literal declaration?](https://stackoverflow.com/q/4616202/1048572) – Bergi May 13 '18 at 12:01

2 Answers2

2

You can use a getter to implement what you want:

var a={
   name:"Rhona",
   get check(){
          return this.name;
            }
   }
1

The IIFE is executed immediately (that's the first "I"¹). Since you're calling it without doing anything particular to set this, this defaults to the global object (in loose mode) or undefined (in strict mode). (See How does the “this” keyword work?)

You're basically doing this, but without a temporary variable:

var temp = (function() {
    return this.name;
})();
var a = {
    name: "Rhona",
    check: temp
}
console.log(a.check) // This returns ""

The reason you get "" rather than undefined is that you're using loose mode, and so this refers to the global object, which is the window on browsers, and the window has a name property (the name of the current window) which is usually empty ("").


¹ The first "I" in "IIFE" is either "Inline" or "Immediately" depending on who you ask. :-) E.g., "Inline-Invoked Function Expression" or "Immediately-Invoked Function Expression".

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • Hmm, I never heard of it being called "inline" but I guess it makes sense. Although, I think "immediately" is more to the point since, as you explain, it is indeed *immediate* when the script is executed, whereas "inline" does not really come across the same way. – VLAZ May 13 '18 at 11:37
  • @vlaz: I've always preferred "immediately-" as well. – T.J. Crowder May 13 '18 at 11:38