The context (this) is naturally the object that the property is being requested on, but there are no arguments passed to the getter function. I’d like to be able to get the name of the property being requested without using closures but it’s looking like that’s the only way to do it.
Object.defineProperty( someObj, "prop1", { get: genericGetter } );
Object.defineProperty( someObj, "prop2", { get: genericGetter } );
function genericGetter() {
// i want to figure out whether this is called on prop1 or prop2
}
That’s not how getters work. A property of an object can either have a
valueor agetfunction. If the property has avalue, then reading the property:returns that
value. However, if a property has agetfunction instead, then reading that property triggers that function. So, you use getters if the value of a certain property has to be computed dynamically, or if you want to perform certain operations whenever the property is read.For instance,
.innerHTMLrequires a getter, because its value is not stored statically, but computed on access:Here, the browser has to serialize the DOM structure that is contained within the
divelement.So, if you want a
.get()function that retrieves various properties (Backbone.js has such a function), then you’re not looking for getters.The simplest implementation of what you want would be: