The get
defines a property accessor function. When the value of the foo
property on o
is retrieved, that function is called even though it doesn't look like a function call in the code, e.g.:
var a = o.foo; // Note that `foo` doesn't have () after it, it's not a function call
In this case, it always returns 17, but it could do something else instead. For instance, consider a circle:
var circle = {
radius: 7,
get circumference() { return 2 * Math.PI * this.radius; },
get area() { return Math.PI * this.radius * this.radius; }
};
console.log(circle.circumference); // 43.982297150257104
console.log(circle.area); // 153.93804002589985
circle.radius = 4;
console.log(circle.circumference); // 25.132741228718345
console.log(circle.area); // 50.26548245743669
As you can see, when we access the two properties we defined with accessors, the functions assigned to them get called, even though the property access doesn't look like a function call.
You can also have functions that get called when the property is set. Unsurprisingly, you do that using set
rather than get
. :-)
You can read more about this in the object initializers part of the specification, and on MDN.
The Object.getOwnPropertyDescriptor
call returns an object that describes the property you asked for (in this case, foo
). You can read more about it in the spec and on MDN as well.
Quoting from MDN:
A property descriptor is a record (TJC: e.g., object) with some of the following attributes:
value
The value associated with the property (data descriptors only).
writable
true
if and only if the value associated with the property may be changed (data descriptors only).
get
A function which serves as a getter for the property, or undefined
if there is no getter (accessor descriptors only).
set
A function which serves as a setter for the property, or undefined
if there is no setter (accessor descriptors only).
configurable
true
if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
enumerable
true
if and only if this property shows up during enumeration of the properties on the corresponding object.