高级对象创建 (Visual Studio - JScript)

JScript 支持对自定义的基于原型的对象的继承。 通过继承,基于原型的对象可以共享一组可动态添加或移除的通用属性和方法。 而且,各个对象都可以重写默认的行为。

创建基于原型的对象

要创建基于原型的对象的实例,首先必须定义一个构造函数。 有关更多信息,请参见 用构造函数创建自己的对象。 一旦编写了此构造函数,就可以使用 prototype 对象(它本身就是每个构造函数的一项属性)的属性来创建继承属性和共享方法。 构造函数可以向对象提供实例特定的信息,而 prototype 对象可以向对象提供对象特定的信息和方法。

提示

若要影响对象的所有实例,必须对构造函数的 prototype 对象进行更改。 更改对象的一个实例的 prototype 属性对同一对象的其他实例没有影响。

由于 prototype 对象的属性和方法是通过引用对象的每个实例的内容而复制的,因此所有的实例都可以访问同样的信息。 可以更改一个实例中一个原型属性的值,以重写默认值,但此更改只影响这一个实例。 下面的实例使用了自定义的构造函数 Circle。 this 语句使此方法能够访问该对象的各个成员。

// Define the constructor and add instance specific information.
function Circle (radius) {
    this.r = radius;  // The radius of the circle.
}
// Add a property the Circle prototype.
Circle.prototype.pi = Math.PI;
function ACirclesArea () {
   // The formula for the area of a circle is pi*r^2.
   return this.pi * this.r * this.r; 
}
// Add a method the Circle prototype.
Circle.prototype.area = ACirclesArea;
// This is how you would invoke the area function on a Circle object.
var ACircle = new Circle(2);
var a = ACircle.area();

利用这一原则,可以为现有的构造函数(它们都具有原型对象)定义其他属性。 只有在关闭快速模式时这才有效。 有关更多信息,请参见 /fast

例如,如果想要移除字符串前面和后面的空格(类似于 Visual Basic 中的 Trim 函数),可以在 String 原型对象上创建您自己的方法,则脚本中的所有字符串都将自动继承此方法。 下面示例使用正则表达式来移除这些空格。 有关更多信息,请参见正则表达式对象

// Add a function called trim as a method of the prototype 
// object of the String constructor.
String.prototype.trim = function() {
   // Use a regular expression to replace leading and trailing 
   // spaces with the empty string
   return this.replace(/(^\s*)|(\s*$)/g, "");
}

// A string with spaces in it
var s = "    leading and trailing spaces    ";
print(s + " (" + s.length + ")");

// Remove the leading and trailing spaces
s = s.trim();
print(s + " (" + s.length + ")");

当使用 /fast- 标志编译该程序后,该程序的输出为:

    leading and trailing spaces     (35)
leading and trailing spaces (27)

请参见

其他资源

基于原型的对象

JScript 对象