1. 对象字面量
1 var myObjectLiteral = { 2 3 variableKey: variableValue, 4 5 functionKey: function () { 6 // ... 7 } 8 };
示例如下:
1 var myModule = { 2 3 myProperty: "someValue", 4 5 // object literals can contain properties and methods. 6 // e.g we can define a further object for module configuration: 7 myConfig: { 8 useCaching: true, 9 language: "en" 10 }, 11 12 // a very basic method 13 saySomething: function () { 14 console.log( "Where in the world is Paul Irish today?" ); 15 }, 16 17 // output a value based on the current configuration 18 reportMyConfig: function () { 19 console.log( "Caching is: " + ( this.myConfig.useCaching ? "enabled" : "disabled") ); 20 }, 21 22 // override the current configuration 23 updateMyConfig: function( newConfig ) { 24 25 if ( typeof newConfig === "object" ) { 26 this.myConfig = newConfig; 27 console.log( this.myConfig.language ); 28 } 29 } 30 }; 31 32 // Outputs: Where in the world is Paul Irish today? 33 myModule.saySomething(); 34 35 // Outputs: Caching is: enabled 36 myModule.reportMyConfig(); 37 38 // Outputs: fr 39 myModule.updateMyConfig({ 40 language: "fr", 41 useCaching: false 42 }); 43 44 // Outputs: Caching is: disabled 45 myModule.reportMyConfig();