什么是“存取功能”?

use*_*159 1 javascript

在标准 ECMA-262 版本的第 4.3.26 节中

根据属性的形式,值可以直接表示为数据值(原始值、对象或函数对象),也可以通过一对访问器函数间接表示。

我不明白“访问器函数”是什么意思,也没有在规范中找到访问器函数的定义。然后我在网上搜索。在我看来,访问器函数的意思是“getter”。但我还是不明白,为什么属性值是“由一对访问器函数”表示的?谁能用例子来说明这一点?谢谢!

lex*_*ore 5

“一对访问器函数”是 getter 和 setter。

文档和示例

var o = {}; // Creates a new object

// Example of an object property added with defineProperty with an accessor property descriptor
var bValue = 38;
Object.defineProperty(o, 'b', {
  get: function() { return bValue; },
  set: function(newValue) { bValue = newValue; },
  enumerable: true,
  configurable: true
});
Run Code Online (Sandbox Code Playgroud)


Ber*_*rgi 5

访问器属性是根据 getter 和 setter 定义的属性,而不是可写入的存储值。“访问函数对”表示 getter 函数和 setter 函数。

\n\n

有关这方面的更多信息可以在\xc2\xa78.6 节中找到:

\n\n
\n

对象是属性的集合。每个属性都是命名数据属性、命名访问器属性或内部属性:\n

\n\n
    \n
  • 命名数据属性将名称与 ECMAScript 语言值和一组布尔属性相关联。
  • \n
  • 命名访问器属性将名称与一个或两个访问器函数以及一组布尔属性相关联。访问器函数用于存储或检索与属性关联的 ECMAScript 语言值。
  • \n
  • 内部属性没有名称,并且不能通过 ECMAScript 语言运算符直接访问。内部属性的存在纯粹是为了规范目的。
  • \n
\n
\n\n

\xc2\xa7 8.6.1 节

\n\n
\n

命名访问器属性将名称与下表中列出的属性相关联:

\n\n
Attribute| Value     | Description\n Name    |  Domain   |\n---------+-----------|---------------------------------------------------------\n[[Get]]  | Object or | If the value is an Object it must be a function Object.\n         | Undefined | The function\xe2\x80\x99s [[Call]] internal method (8.6.2) is\n         |           | called with an empty arguments list to return the\n         |           | property value each time a get access of the property is \n         |           | performed.\n         |           |\n[[Set]]  | Object or | If the value is an Object it must be a function Object.\n         | Undefined | The function\xe2\x80\x99s [[Call]] internal method (8.6.2) is\n         |           | called with an arguments list containing the assigned\n         |           | value as its sole argument each time a set access of the\n         |           | property is performed. The effect of a property\'s\n         |           | [[Set]] internal method may, but is not required to,\n         |           | have an effect on the value returned by subsequent calls\n         |           | to the property\'s [[Get]] internal method.\n         |           |\n[[Enume- | Boolean   | If true, the property is to be enumerated by a for-in\n rable]] |           | enumeration (see 12.6.4). Otherwise, the property is\n         |           | said to be non-enumerable.\n         |           |\n[[Confi- | Boolean   | If false, attempts to delete the property, change the\ngurable]]|           | property to be a data property, or change its attributes\n         |           | will fail.\n
Run Code Online (Sandbox Code Playgroud)\n
\n