存档

文章标签 ‘JavaScript’

对于构造函数的理解

2009年2月16日

在JavaScript的帮助手册里查到的解释是这样的:

一种 JScript 函数,具有两个特殊的性质:

  • new 运算符来调用此函数。
  • 通过 this 关键字将新创建对象的地址传递到此函数。

请使用构造函数来初始化新的对象。

在JS权威指南里看的解释是:

New创建了一个新的没有任何属性的对象,然后调用该函数,把新的对象作为this关键字的值传递。设计来和new运算符一起使用的函数叫做构造函数 ( constructor function 或 constructor )。

下面来创建一个构造函数然后使用 new 运算符调用它两次来创建两个新的对象:

function Rectangle ( w , y ){

this.widht = w;

this.height = h;

}

var rect1 = new Rectangle ( 2 , 4 );  // rect1 = { width = 2, heithg = 4 };

var rect2 = new Rectangle ( 8.5 , 11 );  // rect1 = { width = 8.4, heithg = 11 };

this 语句,来源 JavaScript 的帮助手册

this 语句@import url(../html-vss/msdnie4a.css);指当前对象。

this.property

必选的 property 参数指的是对象的属性。

说明

this 关键字通常在对象的 构造函数中使用,用来引用对象。

示例

在下面示例中,this 指的是新创建的 Car 对象,并给三个属性赋值。

function Car(color, make, model){
  this.color = color;
  this.make = make;
  this.model = model;
}

kingabird JavaScript ,