属性访问器
属性访问器使用点符号或方括号符号提供对对象属性的访问。
¥Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
Try it
语法
描述
¥Description
人们可以将对象视为关联数组(也称为映射、字典、哈希、查找表)。该数组中的键是对象的 properties 的名称。
¥One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of the object's properties.
访问属性有两种方法:点表示法和括号表示法。
¥There are two ways to access properties: dot notation and bracket notation.
点符号
¥Dot notation
在 object.propertyName
语法中,propertyName
必须是有效的 JavaScript identifier,也可以是 保留字。例如,object.$1
有效,而 object.1
无效。
¥In the object.propertyName
syntax, the propertyName
must be a valid JavaScript identifier which can also be a reserved word. For example, object.$1
is valid, while object.1
is not.
const variable = object.propertyName;
object.propertyName = value;
const object = {};
object.$1 = "foo";
console.log(object.$1); // 'foo'
const object = {};
object.1 = 'bar'; // SyntaxError
console.log(object.1); // SyntaxError
这里,从 document
中检索并调用名为 createElement
的方法。
¥Here, the method named createElement
is retrieved from document
and is called.
document.createElement("pre");
如果你使用数字文字的方法,并且数字文字没有指数和小数点,则应在方法调用之前的点之前保留 空白,以便该点不会被解释为小数点。
¥If you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the method call, so that the dot is not interpreted as a decimal point.
77 .toExponential();
// or
77
.toExponential();
// or
(77).toExponential();
// or
77..toExponential();
// or
77.0.toExponential();
// because 77. === 77.0, no ambiguity
此外,私有属性 只能在定义它们的类中使用点表示法进行访问。
¥In addition, private properties can only be accessed using dot notation within the class that defines them.
括号表示法
¥Bracket notation
在 object[expression]
语法中,expression
应计算为表示属性名称的字符串或 符合。因此,它可以是任何字符串文字,例如,包括 '1foo'
、'!bar!'
甚至 ' '
(空格)。
¥In the object[expression]
syntax, the expression
should evaluate to a string or Symbol that represents the property's name. So, it can be any string literal, for example, including '1foo'
, '!bar!'
, or even ' '
(a space).
const variable = object[propertyName];
object[propertyName] = value;
这与前面的示例执行完全相同的操作。
¥This does the exact same thing as the previous example.
document["createElement"]("pre");
括号符号前允许有空格。
¥A space before bracket notation is allowed.
document ["createElement"]("pre");
传递计算结果为属性名称的表达式将执行与直接传递属性名称相同的操作。
¥Passing expressions that evaluate to property name will do the same thing as directly passing the property name.
const key = "name";
const getKey = () => "name";
const Obj = { name: "Michel" };
Obj["name"]; // returns "Michel"
Obj[key]; // evaluates to Obj["name"], and returns "Michel"
Obj[getKey()]; // evaluates to Obj["name"], and returns "Michel"
但是,请注意使用方括号来访问其名称由外部输入指定的属性。这可能会使你的代码容易受到 对象注入攻击 的影响。
¥However, beware of using square brackets to access properties whose names are given by external input. This may make your code susceptible to object injection attacks.
属性名称
¥Property names
每个属性名称都是一个字符串或 符合。任何其他值(包括数字)都会被强制转换为字符串。由于 1
被强制转换为 '1'
,因此输出 'value'
。
¥Each property name is a string or a Symbol. Any other value, including a number, is coerced to a string. This outputs 'value'
, since 1
is coerced into '1'
.
const object = {};
object["1"] = "value";
console.log(object[1]);
这也会输出 'value'
,因为 foo
和 bar
都转换为相同的字符串 ("[object Object]"
)。
¥This also outputs 'value'
, since both foo
and bar
are converted to the same string ("[object Object]"
).
const foo = { uniqueProp: 1 };
const bar = { uniqueProp: 2 };
const object = {};
object[foo] = "value";
console.log(object[bar]);
方法绑定
¥Method binding
当谈到对象的属性时,通常会区分属性和方法。然而,属性/方法的区别只不过是一种约定。方法是可以调用的属性(例如,如果它具有对 Function
实例的引用作为其值)。
¥It's typical when speaking of an object's properties to make a distinction between properties and methods. However, the property/method distinction is little more than a convention. A method is a property that can be called (for example, if it has a reference to a Function
instance as its value).
方法不绑定到它所属的对象。具体来说,this
并不固定在方法中,也不一定指的是包含该方法的对象。相反,通过函数调用,this
是 "passed"。参见 this
的参考。
¥A method is not bound to the object that it is a property of. Specifically, this
is not fixed in a method and does not necessarily refer to the object containing the method. Instead, this
is "passed" by the function call. See the reference for this
.
示例
括号表示法与 eval()
¥Bracket notation vs. eval()
JavaScript 新手经常犯使用 eval()
的错误,而可以使用方括号表示法代替。
¥JavaScript novices often make the mistake of using eval()
where the bracket notation can be used instead.
例如,以下语法在许多脚本中经常出现。
¥For example, the following syntax is often seen in many scripts.
const x = eval(`document.forms.form_name.elements.${strFormControl}.value`);
eval()
速度较慢,应尽可能避免。此外,strFormControl
必须包含一个标识符,而表单控件的名称和 id
则不需要该标识符。最好使用括号表示法:
¥eval()
is slow and should be avoided whenever possible. Also, strFormControl
would have to hold an identifier, which is not required for names and id
s of form controls. It is better to use bracket notation instead:
const x = document.forms.form_name.elements[strFormControl].value;
规范
Specification |
---|
ECMAScript Language Specification # sec-property-accessors |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also