用构造函数创建自己的对象
JScript 的一个强大功能是能够定义构造函数,以创建自定义的基于原型的对象,以便在您的脚本中使用。 要创建基于原型的对象的实例,首先必须定义一个构造函数。 此过程将创建一个新对象并将它初始化(创建属性并赋初始值)。 当完成后,构造函数将返回对所构造对象的引用。 在构造函数内部,创建的对象是通过 this 语句引用的。
具有属性的构造函数
下面的示例为 pasta 对象定义了一个构造函数。 this 语句允许构造函数初始化该对象。
// pasta is a constructor that takes four parameters.
function pasta(grain, width, shape, hasEgg) {
this.grain = grain; // What grain is it made of?
this.width = width; // How many centimeters wide is it?
this.shape = shape; // What is the cross-section?
this.hasEgg = hasEgg; // Does it have egg yolk as a binder?
}
在定义对象构造函数后,使用 new 运算符创建对象的实例。 此处使用 pasta 构造函数创建 spaghetti 和 linguine 对象。
var spaghetti = new pasta("wheat", 0.2, "circle", true);
var linguine = new pasta("wheat", 0.3, "oval", true);
可以动态地为对象的某个实例添加属性,但这些更改只影响这一个实例。
// Additional properties for spaghetti. The properties are not added
// to any other pasta objects.
spaghetti.color = "pale straw";
spaghetti.drycook = 7;
spaghetti.freshcook = 0.5;
如果想为对象的所有实例都添加额外的属性而不修改构造函数,则可以将该属性添加到构造函数的原型对象。 有关更多信息,请参见 高级对象创建 (Visual Studio - JScript)。
// Additional property for all pasta objects.
pasta.prototype.foodgroup = "carbohydrates";
具有方法的构造函数
可以在对象的定义中包含方法(函数)。 做到这一点的一种方法是,在构造函数中包含一个属性,而此属性引用其他地方定义的函数。 像构造函数一样,这些函数也用 this 语句引用当前的对象。
下面的示例扩展前面定义的 pasta 构造函数以包含 toString 方法,当函数显示对象的值时将会调用此方法。 (通常,在要求字符串的条件下使用对象时,JScript 将使用对象的 toString 方法。 很少需要显式调用 toString 方法。)
// pasta is a constructor that takes four parameters.
// The properties are the same as above.
function pasta(grain, width, shape, hasEgg) {
this.grain = grain; // What grain is it made of?
this.width = width; // How many centimeters wide is it?
this.shape = shape; // What is the cross-section?
this.hasEgg = hasEgg; // Does it have egg yolk as a binder?
// Add the toString method (defined below).
// Note that the function name is not followed with parentheses;
// this is a reference to the function itself, not a function call.
this.toString = pastaToString;
}
// The function to display the contents of a pasta object.
function pastaToString() {
return "Grain: " + this.grain + "\n" +
"Width: " + this.width + " cm\n" +
"Shape: " + this.shape + "\n" +
"Egg?: " + Boolean(this.hasEgg);
}
var spaghetti = new pasta("wheat", 0.2, "circle", true);
// Call the method explicitly.
print(spaghetti.toString());
// The print statement takes a string as input, so it
// uses the toString() method to display the properties
// of the spaghetti object.
print(spaghetti);
这样将显示下面的输出。
Grain: wheat
Width: 0.2 cm
Shape: circle
Egg?: true
Grain: wheat
Width: 0.2 cm
Shape: circle
Egg?: true