非常教程

JavaScript参考手册

对象 | Object

object.__defineSetter__

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

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

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

语法

obj.__defineSetter__(prop, fun)

参数

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

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

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

规范

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()
  1. Object.prototype.__lookupGetter__()
  1. Object.prototype.__lookupSetter__()
  1. JS Guide: Defining Getters and Setters
  1. [Blog Post] Deprecation of __defineGetter__ and __defineSetter__
  1. bug 647423

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__

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络