7.1. Creating Objects 创建对象

Objects are composite datatypes: they aggregate multiple values into a single unit and allow you to store and retrieve those values by name. Another way to explain this is to say that an object is an unordered collection of properties, each of which has a name and a value. The named values held by an object may be primitive values, such as numbers and strings, or they may themselves be objects.

(对象是一种复合的数据类型:它将多种数值聚集在一个单元中,并且允许你通过名字存进和取出这些值,另一种解释它的方式是:一个对象是一个无序的属性组成的集合,每一个属性都会有自己的名字和值。存储在对象中的已命名的值可以是原始值,如 numbers 和strings 也可以是对象)

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. Here are some examples:

(最简单的创建对象的方式是在你的javascript代码中包含一个对象直接量。对象之间量是由逗号分隔的属性名/值对列表,包含在大括号之内。任何属性名都可以是一个javascript标识符或是一个string,任何一个属性值都可以是一个常量或任意的javaScript 表达式。这里有几个例子)

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': "[email protected]"
};

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.

(对象直接量是个每次都会创建一个新的不同对象的表达式,也就是说 单个对象直接量可以创建很多新的对象,如果它出现在被重复调用的一个函数 的loop循环体内。)

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. For example:

var a = new Array(); // Create an empty array
var d = new Date();  // Create an object representing the current date and time
var r = new RegExp("javascript", "i");  // Create a pattern-matching object

 

The Array(), Date(), and RegExp() constructors shown above are a built-in part of core JavaScript. (The Array() constructor is described later in this chapter, and you can look up the others in Part III.) The Object() constructor creates an empty object, just as the literal {} does.

It is also possible to define your own constructor functions in order to initialize newly created objects in whatever way you'd like.

你可能感兴趣的:(JavaScript,UP)