Object.prototype.__defineGetter__()
Warning: This feature is deprecated in favor of defining getters using the object initializer syntax or the Object.defineProperty()
API. While this feature is widely implemented, it is only described in the ECMAScript specification because of legacy usage. This method should not be used since better alternatives exist.
The __defineGetter__
method binds an object's property to a function to be called when that property is looked up.
Syntax
__defineGetter__(prop, func)
Parameters
prop
-
A string containing the name of the property to bind to the given function.
func
-
A function to be bound to a lookup of the specified property.
Return value
Description
The __defineGetter__
allows a getter to be defined on a pre-existing object.
Examples
Non-standard and deprecated way
var o = {}; o.__defineGetter__('gimmeFive', function() { return 5; }); console.log(o.gimmeFive); // 5
Standard-compliant ways
// Using the get operator var o = { get gimmeFive() { return 5; } }; console.log(o.gimmeFive); // 5 // Using Object.defineProperty var o = {}; Object.defineProperty(o, 'gimmeFive', { get: function() { return 5; } }); console.log(o.gimmeFive); // 5
Specifications
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
__defineGetter__ |
1 |
12 |
1
Starting with Firefox 48, this method can no longer be called at the global scope without any object. A
TypeError will be thrown otherwise. Previously, the global object was used in these cases automatically, but this is no longer the case. |
11 |
9.5 |
3 |
1 |
18 |
4 |
10.1 |
1 |
1.0 |
See also
- A polyfill of
Object.prototype.__defineGetter__
is available incore-js
Object.prototype.__defineSetter__()
-
get
operator Object.defineProperty()
Object.prototype.__lookupGetter__()
Object.prototype.__lookupSetter__()
- JS Guide: Defining Getters and Setters
- [Blog Post] Deprecation of __defineGetter__ and __defineSetter__
- bug 647423
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__