ILIAS ILIAS - 7 months ago 8
Javascript Question

When is the object returned form a get created?

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
?

Answer

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.

Comments