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

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

例子:

第八章 8.2 构造函数(Constructors)// Define the constructor.
第八章 8.2 构造函数(Constructors)//
 Note how it initializes the object referred to by "this".
第八章 8.2 构造函数(Constructors)
function Rectangle(w, h)
第八章 8.2 构造函数(Constructors){
第八章 8.2 构造函数(Constructors)    
this.width = w;
第八章 8.2 构造函数(Constructors)    
this.height = h;
第八章 8.2 构造函数(Constructors)}
第八章 8.2 构造函数(Constructors)
第八章 8.2 构造函数(Constructors)
// Invoke the constructor to create two Rectangle objects.
第八章 8.2 构造函数(Constructors)//
 We pass the width and height to the constructor,
第八章 8.2 构造函数(Constructors)//
 so it can initialize each new object appropriately.
第八章 8.2 构造函数(Constructors)
var rect1 = new Rectangle(24);
第八章 8.2 构造函数(Constructors)
var rect2 = new Rectangle(8.511);

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

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

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

相关文章:

  • 2021-12-08
  • 2021-10-17
  • 2021-11-18
  • 2021-09-04
  • 2021-06-13
  • 2022-12-23
  • 2021-07-11
猜你喜欢
  • 2021-11-11
  • 2022-12-23
  • 2021-12-03
  • 2022-12-23
  • 2021-05-05
  • 2022-12-23
  • 2021-08-13
相关资源
相似解决方案