Object.prototype.__defineGetter__()

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

JavaScript
<var>obj</var>.__defineGetter__(<var>prop</var>, <var>func</var>)

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

undefined.

Description

The __defineGetter__ allows a getter to be defined on a pre-existing object.

Examples

JavaScript
// 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

Specification Status Comment
ECMAScript 2017 Draft (ECMA-262)
The definition of 'Object.prototype.__defineGetter__()' in that specification.
Draft Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) 11 (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) ? (Yes) (Yes)

Compatibility notes

  • Starting with Firefox 48 (Firefox 48 / Thunderbird 48 / SeaMonkey 2.45), 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 (bug 1253016).

See also

License

© 2016 Mozilla 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__

Deprecated JavaScript Method Object Prototype