在线文档教程

object.__defineSetter__

object.__defineSetter__

该特性是非标准的,请尽量不要在生产环境中使用它!

该特性已经从 Web 标准中删除,虽然一些浏览器目前仍然支持它,但也许会在未来的某个时间停止支持,请尽量不要使用该特性。

__defineSetter__方法可以将一个函数绑定在当前对象的指定属性上,当那个属性被赋值时,你所绑定的函数就会被调用。

语法

obj.__defineSetter__(prop, fun)

参数

prop一个字符串,表示指定的属性名。

function(val) { . . . }

val任意的参数名,在 fun 被调用时,该参数的值就是尝试给sprop属性所赋的值。

返回值

undefined.

描述

__defineSetter__方法可以为一个已经存在的对象设置(新建或修改)访问器属性,而对象字面量中的 set 语法只能在新建一个对象时使用。

示例

// Non-standard and deprecated way var o = {}; o.__defineSetter__('value', function(val) { this.anotherValue = val; } o.value = 5; console.log(o.value // undefined console.log(o.anotherValue // 5 // Standard-compliant ways // Using the set operator var o = { set value(val) { this.anotherValue = val; } }; o.value = 5; console.log(o.value // undefined console.log(o.anotherValue // 5 // Using Object.defineProperty var o = {}; Object.defineProperty(o, 'value', { set: function(val) { this.anotherValue = val; } } o.value = 5; console.log(o.value // undefined console.log(o.anotherValue // 5

规范

SpecificationStatusComment
ECMAScript Latest Draft (ECMA-262)The definition of 'Object.prototype.__defineSetter__()' in that specification.Living StandardIncluded in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).

浏览器兼容性

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic Support(Yes)(Yes)(Yes)111(Yes)(Yes)

FeatureAndroidChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
Basic Support(Yes)(Yes)(Yes)(Yes)(Yes)(Yes)(Yes)

  • 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.See also

  • Object.prototype.__defineGetter__()

  • set operator

  • Object.defineProperty()

  • Object.prototype.__lookupGetter__()

  • Object.prototype.__lookupSetter__()

Edit this page on MDN

© 2005–2017 Mozilla Developer Network and individual 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/__defineSetter__