首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

object.__defineSetter__

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

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

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

语法

代码语言:javascript
复制
obj.__defineSetter__(prop, fun)

参数

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

fun一个函数,当试图去为sprop属性赋值时被调用。通常你要给这个函数指定一个参数:

代码语言:javascript
复制
function(val) { . . . }

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

返回值

undefined.

描述

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

示例

代码语言:javascript
复制
// 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

规范

Specification

Status

Comment

ECMAScript Latest Draft (ECMA-262)The definition of 'Object.prototype.__defineSetter__()' in that specification.

Living Standard

Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

(Yes)

(Yes)

(Yes)1

11

(Yes)

(Yes)

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

  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.See also
  1. Object.prototype.__defineGetter__()
  1. set operator
  1. Object.defineProperty()
代码语言:txt
复制
 © 2005–2017 Mozilla Developer Network and individual contributors.

Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.

扫码关注腾讯云开发者

领取腾讯云代金券