第八章 8.2 构造函数(Constructors)

constructor 是具有下列两个特征的一种 JavaScript 函数:

1. 通过 new 被调用。
2. 被隐式传递了一个引用, 叫做 this. 这个引用指向一个新创建的空的对象。构造函数要负责对该对象进行必要的初始化。

例子:

None.gif //  Define the constructor.
None.gif//
 Note how it initializes the object referred to by "this".
None.gif
function  Rectangle(w, h)
None.gif{
None.gif    
this .width  =  w;
None.gif    
this .height  =  h;
None.gif}
None.gif
None.gif
//  Invoke the constructor to create two Rectangle objects.
None.gif//
 We pass the width and height to the constructor,
None.gif//
 so it can initialize each new object appropriately.
None.gif
var  rect1  =   new  Rectangle( 2 4 );
None.gif
var  rect2  =   new  Rectangle( 8.5 11 );

记住,一个 constructor 函数仅仅需要对对象进行初始化,而不一定要返回这个对象。

因为每个 constructor 返回一种类型的对象,给 constructor 函数一个表示类名称的命名是很有意义的。比如要创建一个矩形对象:new Rectangle(1, 2) 显然比 new init_rect(1, 2) 这样的命名要好的多。

constructor 通常是不返回值的。但也可以返回一个 object 值。如果这样做,则返回的值变成了 new 表达式的结果。而 this 指代的那个原先的对象被简单的丢弃了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值