This article describes the two points of JavaScript objects: Dynamic selection methods and properties, traversing object properties and methods, the need for friends can refer to the following
(i) Dynamic selection methods and properties in practice, we often encounter situations where we invoke one of two methods [1] According to a certain condition, or read and write on one of the two properties [2]. The following code shows this scenario: code as follows: if (condition) { myobj.method1 (somearg); } else { myobj.method2 ( Somearg); } JavaScript provides a simple syntax for dynamically selecting methods and properties using the square bracket operator ([]). As the following code shows, JavaScript has two equivalent member access syntax (this feature is common in dynamic languages): obj[expressionresultinginmembername] = = Obj.membername If you've ever used an integer subscript to access an element in an array, you've started using the bracket operator for dynamic member selection. This is because the array object itself contains the attributes (and the length property) that are named after the number subscript. However, JavaScript does not allow you to use the dot operator (.) To access these properties directly, so myarray.0 is syntactically illegal (which, sadly, would have been a pretty cool syntax). Why is the square bracket operator more powerful than the dot operator notation? This is because you can access the members of an object in square brackets using any content that represents the name of the member. These include literal values, variables that hold member names, combinations of names (in most cases concatenation of strings), and ternary operators (condition?). Valueiftrue:valueiffalse) Implementation of the fast If/then selection. All of this content will be processed into a string, and JavaScript will use this string to find the corresponding member. Because a function in JavaScript itself is also an object, it can be referenced like any other value. If the result of an expression is a function, you can call it directly with the parentheses operator, just as you would call a function directly with the function name. Note that if you use such techniques extensively in the parameters passed to the method, the confusion of parentheses may make the code unreadable, and it is wiser to use a regular if/else structure at this time. (ii) JavaScript traversal object properties and methods JavaScript makesIterate through the object's properties and methods with the for in statement. The for in statement loops through the JavaScript object, and each time the loop gets a property or method of the object. Syntax: code as follows: for (ValueName in objectname) { //code } where, ValueName is the variable name, save the attribute or the name of the method, with each loop, the value of the valuename changes.