ECMA-262 5.1 Edition中关于对象的创建
在ECMA-262 5.1 Edition的开始部分描述了关于对象的创建,它是这样描述的:
ECMAScript does not use classes such as those in C++, Smalltalk, or Java. Instead objects may be created in various ways including via a literal notation or via constructors which create objects and then execute code that initialises all or part of them by assigning initial values to their properties. Each constructor is a function
that has a property named ”prototyp” that is used to implement prototype-based inheritance and shared properties. Objects are created by using constructors in new expressions; for example, new Date(2009,11) creates a new Date object. Invoking a constructor without using new has consequences that depend on the constructor. For example, Date() produces a string representation of the current date and time rather than an object.Every object created by a constructor has an implicit reference (called the object‘s prototype) to the value of its constructor‘s ”prototyp” property. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain. When a reference is made to a property in an object,that reference is to the property of that name in the first object in the prototype chain that contains a property of that name. In other words, first the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.
其中,介绍了创建对象的两种方式: literal notation(字面量)和constructors (构造器函数)。
通过字面量的方式如下:
var obj={
name:'siege',
age:24
};
通过构造器的方式是使用关键字new来创建对象,例如上文提到的
new Date(2009,11);
其返回值为一个对象,当然,我们也可以不使用关键字来创建对象,例如
Date();
其返回值是当前时间,值类型为string类型。
通过构造器创建的对象有一个隐含的引用(implicit reference),即对象的prototype引用,该引用指向该构造器的prototype属性