Output Method and definition benefit of object literal volume
1. There are two ways to output the object literal: traditional '. ', And the array method,When output in array mode, square brackets must be enclosed in quotation marks, as shown in figure
VaRBox ={Name: 'abc'; age:28}; Alert (Box ['name']);
Define methods for objects,
A:If you useTraditional definition objectMethod,You need to define the method first, and then assign the method name to an attribute of the object.,If you want to call this method without parentheses, It is the return method.CodeIf you want to call this method, add brackets to the object property to obtain the return value of the method.
Function Objrun (){ Return '2017 ';} VaR Box = New Object (); box. Name = 'Abc'; box. Age = 28 ; Box. Run = Objrun; alert (box. Run ()); // Result 123 // Alert (box. Run); // The result is function objrun (){ Return '2017 ';} // If box. Run = objrun (); // Alert (box. Run); // The result is 123. If it contains parentheses, an error is returned.
B:Defined literally, OnlyDirectly on this property of the object, writeFunctionThat's all.FunctionThere is no function name above. It is an anonymous function.How can we call this method? Use the property name of the object to call the method, just like above.
For example:
VaRBox ={Name: 'abc', age:28, Run:Function(){Return'2017';}} Alert (box. Run ());
2. Define the object literal volume to easily handle the situations where a large number of function parameters need to be output one by one. His pairThe policy is to input an object to the function, which is defined literally. The relationship between attributes and values can be clearly indicated.Because the function is only a piece of code and must be called before execution.
For example:
FunctionAA (OBJ) {alert (obj. Name); alert (obj. Age );}VaROBJ ={Name:'Abc', Age:28} AA (OBJ );
JS object literal demo
/* ** @ Author Zhanghua */ VaR Literal ={Add: Function () {Alert ( "Add" ) ;}, DEL: Function () {Alert ( "Delete" ) ;}, Update: Function () {Alert ( "Update" ) ;}, Name: "Zhangsan" , Callliteral: Function (){ // This keyword is required for calls to the current literal object. This . Add ();}};
HTML file:
<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml"> /> <Input type = "Button" value = "Caller" onclick = 'javascript: literal. callliteral () '"/> </body>