constructor 是具有下列两个特征的一种 JavaScript 函数:
1. 通过 new 被调用。
2. 被隐式传递了一个引用, 叫做 this. 这个引用指向一个新创建的空的对象。构造函数要负责对该对象进行必要的初始化。
例子:
//
Define the constructor.
// Note how it initializes the object referred to by "this".
function Rectangle(w, h)
{
this .width = w;
this .height = h;
}
// Invoke the constructor to create two Rectangle objects.
// We pass the width and height to the constructor,
// so it can initialize each new object appropriately.
var rect1 = new Rectangle( 2 , 4 );
var rect2 = new Rectangle( 8.5 , 11 );
// Note how it initializes the object referred to by "this".
function Rectangle(w, h)
{
this .width = w;
this .height = h;
}
// Invoke the constructor to create two Rectangle objects.
// We pass the width and height to the constructor,
// so it can initialize each new object appropriately.
var rect1 = new Rectangle( 2 , 4 );
var rect2 = new Rectangle( 8.5 , 11 );
记住,一个 constructor 函数仅仅需要对对象进行初始化,而不一定要返回这个对象。
因为每个 constructor 返回一种类型的对象,给 constructor 函数一个表示类名称的命名是很有意义的。比如要创建一个矩形对象:new Rectangle(1, 2) 显然比 new init_rect(1, 2) 这样的命名要好的多。
constructor 通常是不返回值的。但也可以返回一个 object 值。如果这样做,则返回的值变成了 new 表达式的结果。而 this 指代的那个原先的对象被简单的丢弃了。