At what point is the object {a:1,b:2} created? Is it when the code is initially run or only when obj.prop2 is explicitly accessed?
The object {a:1, b:2} is created when we access obj.prop2, as this triggers the getter function. This results in a new object being returned every time the property is accessed:
var obj={
prop1:7,
get prop2 (){
console.log('I ran');
return {a:1,b:2}
}
};
document.body.innerHTML = obj.prop2 == obj.prop2; // false
Consider the following analogy:
// One:
var obj = {
f: function() {
return {a:1, b:2};
}
};
// Two:
obj.f();
In this scenario, the object {a:1, b:2} is created at "Two:", not at "One:". Each time f() is called, a new object is created.
When we type obj.prop2 in the console, it auto-suggests properties like a and b along with others. How does this work?
The console reads the property to determine its value and provide auto-suggestions, similar to how it handles other properties. For example, in Chrome, you may see "I ran" displayed when typing "." after obj.prop2.
You can test this in your own console environment:
var obj = {
x: 1,
get prop() {
var o = {};
++this.x;
o["___" + this.x] = "foo";
return o;
}
};
Then type
obj.prop.
...and observe the property named ___1. If you delete the ".", then retype it, you will now see the property ___2. The console reads the property each time, invoking the getter function.