This feature is deprecated in favor of defining getters using the object initializer syntax 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.

__defineGetter__ method binds an object's property to a function to be called when that property is looked up.

句法

obj.__defineGetter__(prop, func)
					

参数

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.

返回值

undefined .

描述

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

范例

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
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'Object.prototype.__defineGetter__()' in that specification.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
__defineGetter__ 弃用 Chrome 1 Edge 12 Firefox 1
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.
IE 11 Opera 9.5 Safari 3 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs Yes

图例

完整支持

完整支持

弃用。不要用于新网站。

弃用。不要用于新网站。

见实现注意事项。

另请参阅

元数据

  • 最后修改: