6.2 Querying and Setting Properties
To obtain the value of a property, use the dot (.) or square bracket () operators described in §4.4 . The left-hand side should be an expression whose value is an object. If using the dot operator, the right-hand must be a simple identifier that names the property. If using square brackets, the value within the brackets must be an expression that evaluates to a string that contains the desired property name:
var author = book.author; // Get the "author" property of the book. var name = author.surname // Get the "surname" property of the author. var title = book["main title"] // Get the "main title" property of the book.
To create or set a property, use a dot or square brackets as you would to query the property, but put them on the left-hand side of an assignment expression:
book.edition = 6; // Create an "edition" property of book. book["main title"] = "ECMAScript"; // Set the "main title" property.
In ECMAScript 3, the identifier that follows the dot operator cannot be a reserved word: you cannot write o.foror o.class, for example, because foris a language keyword and class is reserved for future use. If an object has properties whose name is a reserved word, you must use square bracket notation to access them: o["for"] and o["class"]. ECMAScript 5 relaxes this restriction (as do some implementations of ECMAScript 3) and allows reserved words to follow the dot.
When using square bracket notation, we’ve said that the expression inside the square brackets must evaluate to a string. A more precise statement is that the expression must evaluate to a string or a value that can be converted to a string. In Chapter 7 , for example, we’ll see that it is common to use numbers inside the square brackets.欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/27640.html