get
get
语法将对象属性绑定到查找该属性时将调用的函数。也可用于 classes。
¥The get
syntax binds an object property to a function that will be called when that property is looked up. It can also be used in classes.
Try it
语法
参数
¥Parameters
prop
-
要绑定到给定函数的属性的名称。与 对象初始值设定项 中的其他属性一样,它可以是字符串文字、数字文字或标识符。
expression
-
你还可以使用计算属性名称的表达式来绑定到给定的函数。
描述
¥Description
有时,允许访问返回动态计算值的属性是可取的,或者你可能希望反映内部变量的状态而无需使用显式方法调用。在 JavaScript 中,这可以通过使用 getter 来完成。
¥Sometimes, it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. In JavaScript, this can be accomplished with the use of a getter.
对象属性要么是数据属性,要么是访问器属性,但不能同时是两者。阅读 Object.defineProperty()
了解更多信息。getter 语法允许你在对象初始值设定项中指定 getter 函数。
¥An object property is either a data property or an accessor property, but it cannot simultaneously be both. Read Object.defineProperty()
for more information. The getter syntax allows you to specify the getter function in an object initializer.
const obj = {
get prop() {
// getter, the code executed when reading obj.prop
return someValue;
},
};
使用此语法定义的属性是创建的对象自己的属性,并且它们是可配置和可枚举的。
¥Properties defined using this syntax are own properties of the created object, and they are configurable and enumerable.
示例
在对象初始值设定项中为新对象定义 getter
¥Defining a getter on new objects in object initializers
这将为对象 obj
创建一个伪属性 latest
,它将返回 log
中的最后一个数组项。
¥This will create a pseudo-property latest
for object obj
,
which will return the last array item in log
.
const obj = {
log: ["example", "test"],
get latest() {
return this.log.at(-1);
},
};
console.log(obj.latest); // "test"
请注意,尝试为 latest
赋值不会改变它。
¥Note that attempting to assign a value to latest
will not change it.
在类中使用 getter
¥Using getters in classes
你可以使用完全相同的语法来定义类实例上可用的公共实例 getter。在类中,方法之间不需要逗号分隔符。
¥You can use the exact same syntax to define public instance getters that are available on class instances. In classes, you don't need the comma separator between methods.
class ClassWithGetSet {
#msg = "hello world";
get msg() {
return this.#msg;
}
set msg(x) {
this.#msg = `hello ${x}`;
}
}
const instance = new ClassWithGetSet();
console.log(instance.msg); // "hello world"
instance.msg = "cake";
console.log(instance.msg); // "hello cake"
Getter 属性在类的 prototype
属性上定义,因此由该类的所有实例共享。与对象字面量中的 getter 属性不同,类中的 getter 属性是不可枚举的。
¥Getter properties are defined on the prototype
property of the class and are thus shared by all instances of the class. Unlike getter properties in object literals, getter properties in classes are not enumerable.
静态 getter 和私有 getter 使用类似的语法,如 static
和 私有属性 页中所述。
¥Static getters and private getters use similar syntaxes, which are described in the static
and private properties pages.
使用 delete
运算符删除 getter
使用 defineProperty
在现有对象上定义 getter
¥Defining a getter on existing objects using defineProperty
要稍后随时将 getter 附加到现有对象,请使用 Object.defineProperty()
。
¥To append a getter to an existing object later at any time, use
Object.defineProperty()
.
const o = { a: 0 };
Object.defineProperty(o, "b", {
get() {
return this.a + 1;
},
});
console.log(o.b); // Runs the getter, which yields a + 1 (which is 1)
使用计算属性名称
定义静态获取器
智能/自覆盖/惰性获取器
¥Smart / self-overwriting / lazy getters
Getter 为你提供了一种定义对象属性的方法,但在访问该属性之前它们不会计算该属性的值。getter 会推迟计算值的成本,直到需要该值为止。如果从不需要它,你就无需支付费用。
¥Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed. If it is never needed, you never pay the cost.
用于延迟或延迟属性值的计算并将其缓存以供以后访问的附加优化技术是智能(或 memoized)getters。该值在第一次调用 getter 时计算,然后缓存,因此后续访问将返回缓存的值而无需重新计算。这在以下情况下很有用:
¥An additional optimization technique to lazify or delay the calculation of a property value and cache it for later access are smart (or memoized) getters. The value is calculated the first time the getter is called and is then cached so subsequent accesses return the cached value without recalculating it. This is useful in the following situations:
- 如果属性值的计算成本很高(需要大量 RAM 或 CPU 时间、生成工作线程、检索远程文件等)。
- 如果现在不需要该值。它将在稍后使用,或者在某些情况下根本不使用。
- 如果使用它,它将被访问多次,并且不需要重新计算该值永远不会改变或不应该重新计算。
注意:这意味着你不应该为你期望更改其值的属性编写惰性 getter,因为如果 getter 是惰性的,那么它就不会重新计算该值。
¥Note: This means that you shouldn't write a lazy getter for a property whose value you expect to change, because if the getter is lazy, then it will not recalculate the value.
请注意,获取器本质上不是 "lazy" 或 "memoized";如果你想要这种行为,则必须实现此技术。
¥Note that getters are not "lazy" or "memoized" by nature; you must implement this technique if you desire this behavior.
在下面的示例中,该对象有一个 getter 作为其自己的属性。获取属性后,该属性将从对象中删除并重新添加,但这次隐式地作为数据属性。最后,返回值。
¥In the following example, the object has a getter as its own property. On getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. Finally, the value gets returned.
const obj = {
get notifier() {
delete this.notifier;
this.notifier = document.getElementById("bookmarked-notification-anchor");
return this.notifier;
},
};
get 与 DefineProperty
¥get vs. defineProperty
虽然使用 get
关键字和 Object.defineProperty()
具有相似的结果,但在 classes
上使用时两者之间存在细微差别。
¥While using the get
keyword and Object.defineProperty()
have
similar results, there is a subtle difference between the two when used on
classes
.
当使用 get
时,属性将在实例的原型上定义,而使用 Object.defineProperty()
时,属性将在其所应用的实例上定义。
¥When using get
the property will be defined on the instance's prototype,
while using Object.defineProperty()
the property will be defined on the
instance it is applied to.
class Example {
get hello() {
return "world";
}
}
const obj = new Example();
console.log(obj.hello);
// "world"
console.log(Object.getOwnPropertyDescriptor(obj, "hello"));
// undefined
console.log(
Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), "hello"),
);
// { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined }
规范
Specification |
---|
ECMAScript Language Specification # sec-method-definitions |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also
- 处理对象 指南
- 函数
set
Object.defineProperty()
- 对象初始值设定项
class
- 属性访问器
- 杰夫·沃尔登的《不兼容的 ES5 更改:文字 getter 和 setter 函数现在必须恰好有零个或一个参数》(2010)
- 杰夫·沃尔登的《更多 SpiderMonkey 变化:用于创建 getter 和 setter 的古老、深奥、很少使用的语法正在被删除》(2010)