创建对象
1.对象直接量(最简单的创建对象的方式)
The easiest way to create an object is to include an object literal in your JavaScript code. An object literal is a comma-separated list of property name/value pairs, enclosed within curly braces. Each property name can be a JavaScript identifier or a string(标识符和字符串都可以用作属性名), and each property value can be a constant or any JavaScript expression(常量和表达式都可做属性值).
var empty = {}; // An object with no properties
var point = { x:0, y:0 }; //标识符作为属性名
var circle = { x:point.x, y:point.y+1, radius:2 };
var homer = {
"name": "Homer Simpson", // 字符串作为属性名
"age": 34,
"married": true,
"occupation": "plant operator",
'email': homer@example.com
};
An object literal is an expression that creates and initializes a new and distinct object each time it is evaluated. That is, a single object literal can create many new objects if it appears within the body of a loop in a function that is called repeatedly.(对象直接量是一个每次都会创建和初始化一个新的不同的对象的表达式,"好像不通:不知道要怎么翻译了")
2.new 操作符来创建对象
The new operator can create specialized kinds of objects. You follow it with an invocation of a constructor function that initializes the properties of the object. (new操作符后是一个 用于初始化对象属性的构造函数的引用)
var a = new Array();
var d = new Date();
var r = new RegExp("javascript", "i");
Array()、 Date()、 RegExp()是 javascript core 中预定义的一部分构造器,我们也可以定义 自定义的构造函数已任何想要的方式初始化新创建的对象。
Note:The Object() constructor creates an empty object, just as the literal {} does