0

Consider the following code:

var obj={
       prop1:7,
       get prop2 (){
          console.log('I ran');
          return {a:1,b:2}     
       }
}

When is the object {a:1,b:2} getting created?

When the above code is run or when we run explicitly obj.prop2 ? I came upon this query because by writing obj.prop2.a we get 1 and I cannot explain this behavior. If not running obj.prop2 how does it know the value of obj.prop2.a?

Moreover, in console when we just write obj.prop2. it suggests for auto completion, among the other, a and b. How that happens, since we did not run obj.prop2 ?

Unknown developer
  • 5,414
  • 13
  • 52
  • 100

1 Answers1

6

When the object {a:1,b:2} is being created? By just running the above code or when we run explicitly obj.prop2 ?

The latter, when we access obj.prop2, which runs the getter function. Not least because every time you access that, you'll get back a different object:

var obj={
       prop1:7,
       get prop2 (){
          console.log('I ran');
          return {a:1,b:2}     
       }
};
document.body.innerHTML = obj.prop2 == obj.prop2; // false

It's exactly like this:

// One:
var obj = {
    f: function() {
        return {a:1, b:2};
    }
};
// Two:
obj.f();

The object {a:1, b:2} is created at Two:, not One:. And a new one is created every time f() is run.

in console when we just write obj.prop2. it suggests for auto completion, among the other, a and b. How that happens

It reads the property. It's a property, after all, so just like the console reads any other property to get its value and do autosuggest, it reads this property. You can see that with your example (at least on Chrome), because we see "I ran" appear when we hit . after obj.prop2.

Try this in your console:

var obj = {
    x: 1,
    get prop() {
        var o = {};
        ++this.x;
        o["___" + this.x] = "foo";
        return o;
    }
};

Then type

obj.prop.

...and note the property at the top (probably) with the name ___1. Now backspace over the . and press . again. You see a different property, ___2. Do it again and you'll see ___3. That's because the console reads the property, calling the getter function.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • My question would be, why would someone use a getter to return an object? – evolutionxbox Apr 21 '16 at 10:47
  • @evolutionxbox For a lazy object initialization or hide internal implementation. For example obj.__proto__ is a getter. – Dmitri Pavlutin Apr 21 '16 at 10:49
  • Thank you very much for the answer. However, one more thing. I am still not sure if I understand the behavior of running directly `obj.prop2.a` without prior execution of `obj.prop2`. Even in that case `{a:1, b:2}' is created? – Unknown developer Apr 21 '16 at 10:52
  • @ILIAS: Any time the value of `obj.prop2` is read, the getter function is run, returning a new object. – T.J. Crowder Apr 21 '16 at 10:54