将脚本迁移到 V8 运行时

如果您已有使用 Rhino 运行时的脚本,并且想要使用 V8 语法和功能,则必须将脚本迁移到 V8

使用 Rhino 运行时编写的大多数脚本都可以在无需调整的情况下使用 V8 运行时运行。通常,向脚本添加 V8 语法和功能的唯一前提条件是启用 V8 运行时

不过,有一小部分不兼容其他差异可能会导致在启用 V8 运行时后脚本失败或出现意外行为。当您迁移脚本以使用 V8 时,必须在脚本项目中搜索这些问题并更正找到的所有问题。

V8 迁移过程

要将脚本迁移到 V8,请按以下步骤操作:

  1. 为脚本启用 V8 运行时
  2. 仔细查看下面列出的不兼容性。检查您的脚本,确定是否存在任何不兼容问题;如果存在一个或多个不兼容问题,请调整脚本代码以消除或避免此问题。
  3. 仔细查看下面列出的其他差异。 检查您的脚本,确定列出的任何差异是否会影响代码的行为。调整脚本以纠正行为。
  4. 更正了发现的任何不兼容性或其他差异后,您就可以开始更新代码,以便根据需要使用 V8 语法和其他功能
  5. 完成代码调整后,请全面测试您的脚本,确保其行为符合预期。
  6. 如果您的脚本是 Web 应用或已发布的插件,则必须使用 V8 调整创建新版本的脚本。要向用户提供 V8 版本,您必须在此版本中重新发布脚本。

不兼容性

遗憾的是,基于 Rhino 的原始 Apps 脚本运行时允许几种非标准的 ECMAScript 行为。由于 V8 符合标准,因此迁移后将不支持这些行为。一旦启用 V8 运行时,如未能更正这些问题,将会导致出现错误或脚本行为异常。

以下部分分别介绍了在迁移到 V8 期间您需要采取的相应行为和更正脚本代码的步骤。

避免使用 for each(variable in object)

JavaScript 1.6 中添加了 for each (variable in object) 语句,并移除了它,取而代之的是 for...of

将脚本迁移到 V8 时,请避免使用 for each (variable in object) 语句

请改用 for (variable in object)

// Rhino runtime
var obj = {a: 1, b: 2, c: 3};

// Don't use 'for each' in V8
for each (var value in obj) {
  Logger.log("value = %s", value);
}
      
// V8 runtime
var obj = {a: 1, b: 2, c: 3};

for (var key in obj) {  // OK in V8
  var value = obj[key];
  Logger.log("value = %s", value);
}
      

避免使用 Date.prototype.getYear()

在原始的 Rhino 运行时中,Date.prototype.getYear() 返回 1900-1999 年期间的两位数年份,但其他日期返回四位数年份,这是 JavaScript 1.2 及更早版本的行为。

在 V8 运行时中,Date.prototype.getYear() 会根据 ECMAScript 标准的要求,返回年份减 1900 的值。

将脚本迁移到 V8 时,请始终使用 Date.prototype.getFullYear(),它会返回一个四位数年份,而不考虑日期。

避免将预留关键字用作名称

ECMAScript 禁止在函数和变量名称中使用某些预留关键字。Rhino 运行时允许使用其中的许多字词,因此如果您的代码使用了这些字词,您必须重命名函数或变量。

将脚本迁移到 V8 时,请避免使用某个预留关键字来命名变量或函数。重命名任何变量或函数,以避免使用关键字名称。关键字作为名称的常见用法包括 classimportexport

避免为 const 变量重新赋值

在原始 Rhino 运行时中,您可以使用 const 声明变量,这意味着符号的值永远不会改变,并且以后对该符号的赋值会被忽略。

在新的 V8 运行时中,const 关键字符合标准,如果分配给声明为 const 的变量,则会导致 TypeError: Assignment to constant variable 运行时错误。

将脚本迁移到 V8 时,请勿尝试重新赋值 const 变量的值

// Rhino runtime
const x = 1;
x = 2;          // No error
console.log(x); // Outputs 1
      
// V8 runtime
const x = 1;
x = 2;          // Throws TypeError
console.log(x); // Never executed
      

避免使用 XML 字面量和 XML 对象

通过这个针对 ECMAScript 的非标准扩展程序,Apps 脚本项目可以直接使用 XML 语法。

将脚本迁移到 V8 时,请避免使用直接 XML 字面量或 XML 对象

应改为使用 XmlService 来解析 XML:

// V8 runtime
var incompatibleXml1 = <container><item/></container>;             // Don't use
var incompatibleXml2 = new XML('<container><item/></container>');  // Don't use

var xml3 = XmlService.parse('<container><item/></container>');     // OK
      

请勿使用 __iterator__ 构建自定义迭代器函数

JavaScript 1.7 添加了一项功能,允许通过在类的原型中声明 __iterator__ 函数来向任何 cla 添加自定义迭代器;为方便开发者,我们还将该功能添加到了 Apps 脚本的 Rhino 运行时中。但是,此功能从未成为 ECMA-262 标准的一部分,并且已在符合 ECMAScript 的 JavaScript 引擎中移除。使用 V8 的脚本无法使用这种迭代器结构。

将脚本迁移到 V8 时,避免使用 __iterator__ 函数来构建自定义迭代器。请改用 ECMAScript 6 迭代器

请考虑以下数组构造:

// Create a sample array
var myArray = ['a', 'b', 'c'];
// Add a property to the array
myArray.foo = 'bar';

// The default behavior for an array is to return keys of all properties,
//  including 'foo'.
Logger.log("Normal for...in loop:");
for (var item in myArray) {
  Logger.log(item);            // Logs 0, 1, 2, foo
}

// To only log the array values with `for..in`, a custom iterator can be used.
      

以下代码示例展示了如何在 Rhino 运行时中构建迭代器,以及如何在 V8 运行时中构建替换迭代器:

// Rhino runtime custom iterator
function ArrayIterator(array) {
  this.array = array;
  this.currentIndex = 0;
}

ArrayIterator.prototype.next = function() {
  if (this.currentIndex
      >= this.array.length) {
    throw StopIteration;
  }
  return "[" + this.currentIndex
    + "]=" + this.array[this.currentIndex++];
};

// Direct myArray to use the custom iterator
myArray.__iterator__ = function() {
  return new ArrayIterator(this);
}


Logger.log("With custom Rhino iterator:");
for (var item in myArray) {
  // Logs [0]=a, [1]=b, [2]=c
  Logger.log(item);
}
      
// V8 runtime (ECMAScript 6) custom iterator
myArray[Symbol.iterator] = function() {
  var currentIndex = 0;
  var array = this;

  return {
    next: function() {
      if (currentIndex < array.length) {
        return {
          value: "[${currentIndex}]="
            + array[currentIndex++],
          done: false};
      } else {
        return {done: true};
      }
    }
  };
}

Logger.log("With V8 custom iterator:");
// Must use for...of since
//   for...in doesn't expect an iterable.
for (var item of myArray) {
  // Logs [0]=a, [1]=b, [2]=c
  Logger.log(item);
}
      

避免使用条件 catch 子句

V8 运行时不支持 catch..if 条件 catch 子句,因为它们不符合标准。

将脚本迁移到 V8 时,请将所有捕获条件都移到 catch 正文中

// Rhino runtime

try {
  doSomething();
} catch (e if e instanceof TypeError) {  // Don't use
  // Handle exception
}
      
// V8 runtime
try {
  doSomething();
} catch (e) {
  if (e instanceof TypeError) {
    // Handle exception
  }
}

避免使用 Object.prototype.toSource()

JavaScript 1.3 包含的 Object.prototype.toSource() 方法从未包含在任何 ECMAScript 标准中。V8 运行时不支持此功能。

将脚本迁移到 V8 时,请从代码中移除所有 Object.prototype.toSource()

其他差异

除了上述可能导致脚本失败的不兼容性之外,还有其他一些差异,如果不加以更正,可能会导致 V8 运行时脚本出现意外行为。

以下部分介绍了如何更新脚本代码以避免这些意外情况。

调整特定于语言区域的日期和时间格式

Date 方法 toLocaleString()toLocaleDateString()toLocaleTimeString() 在 V8 运行时中的行为不同于 Rhino。

在 Rhino 中,默认格式为长格式,传入的所有参数都会被忽略

在 V8 运行时中,默认格式为短格式,传入的参数根据 ECMA 标准进行处理(如需了解详情,请参阅 toLocaleDateString() 文档)。

将脚本迁移到 V8 时,请针对特定于语言区域的日期和时间方法的输出测试并调整代码预期

// Rhino runtime
var event = new Date(
  Date.UTC(2012, 11, 21, 12));

// Outputs "December 21, 2012" in Rhino
console.log(event.toLocaleDateString());

// Also outputs "December 21, 2012",
//  ignoring the parameters passed in.
console.log(event.toLocaleDateString(
    'de-DE',
    { year: 'numeric',
      month: 'long',
      day: 'numeric' }));
// V8 runtime
var event = new Date(
  Date.UTC(2012, 11, 21, 12));

// Outputs "12/21/2012" in V8
console.log(event.toLocaleDateString());

// Outputs "21. Dezember 2012"
console.log(event.toLocaleDateString(
    'de-DE',
    { year: 'numeric',
      month: 'long',
      day: 'numeric' }));
      

避免使用 Error.fileNameError.lineNumber

在 V8 Untime 版本中,标准 JavaScript Error 对象不支持将 fileNamelineNumber 用作构造函数参数或对象属性。

将脚本迁移到 V8 时,请移除对 Error.fileNameError.lineNumber 的任何依赖项

另一种方法是使用 Error.prototype.stack。此堆栈也是非标准堆栈,但 Rhino 和 V8 均受支持。两个平台生成的堆栈轨迹格式略有不同:

// Rhino runtime Error.prototype.stack
// stack trace format
at filename:92 (innerFunction)
at filename:97 (outerFunction)


// V8 runtime Error.prototype.stack
// stack trace format
Error: error message
at innerFunction (filename:92:11)
at outerFunction (filename:97:5)
      

调整对字符串化枚举对象的处理

在原始 Rhino 运行时中,对枚举对象使用 JavaScript JSON.stringify() 方法仅返回 {}

在 V8 中,对枚举对象使用相同的方法将重获枚举名称。

将脚本迁移到 V8 时,请测试并调整代码对枚举对象的 JSON.stringify() 输出的预期

// Rhino runtime
var enumName =
  JSON.stringify(Charts.ChartType.BUBBLE);

// enumName evaluates to {}
// V8 runtime
var enumName =
  JSON.stringify(Charts.ChartType.BUBBLE);

// enumName evaluates to "BUBBLE"

调整对未定义参数的处理方式

在原始 Rhino 运行时中,将 undefined 作为参数传递给方法会导致将字符串 "undefined" 传递给该方法。

在 V8 中,将 undefined 传递给方法等同于传递 null

将脚本迁移到 V8 时,请测试并调整代码对 undefined 参数的预期

// Rhino runtime
SpreadsheetApp.getActiveRange()
    .setValue(undefined);

// The active range now has the string
// "undefined"  as its value.
      
// V8 runtime
SpreadsheetApp.getActiveRange()
    .setValue(undefined);

// The active range now has no content, as
// setValue(null) removes content from
// ranges.

调整对全局 this 的处理方式

Rhino 运行时为使用它的脚本定义了隐式特殊上下文。脚本代码在此隐式上下文中运行,与实际的全局 this 不同。这意味着,代码中对“全局 this”的引用实际上将评估为特殊上下文,该上下文仅包含脚本中定义的代码和变量。使用 this 时,不会使用内置的 Apps 脚本服务和 ECMAScript 对象。这种情况类似于以下 JavaScript 结构:

// Rhino runtime

// Apps Script built-in services defined here, in the actual global context.
var SpreadsheetApp = {
  openById: function() { ... }
  getActive: function() { ... }
  // etc.
};

function() {
  // Implicit special context; all your code goes here. If the global this
  // is referenced in your code, it only contains elements from this context.

  // Any global variables you defined.
  var x = 42;

  // Your script functions.
  function myFunction() {
    ...
  }
  // End of your code.
}();

在 V8 中,移除了隐式特殊上下文。脚本中定义的全局变量和函数放置在全局上下文中,与内置的 Apps 脚本服务和 ECMAScript 内置项(如 MathDate)并排。

将脚本迁移到 V8 时,请测试并调整代码对全局上下文中使用 this 的预期。在大多数情况下,只有当您的代码检查全局 this 对象的键或属性名称时,差异才会很明显:

// Rhino runtime
var myGlobal = 5;

function myFunction() {

  // Only logs [myFunction, myGlobal];
  console.log(Object.keys(this));

  // Only logs [myFunction, myGlobal];
  console.log(
    Object.getOwnPropertyNames(this));
}





      
// V8 runtime
var myGlobal = 5;

function myFunction() {

  // Logs an array that includes the names
  // of Apps Script services
  // (CalendarApp, GmailApp, etc.) in
  // addition to myFunction and myGlobal.
  console.log(Object.keys(this));

  // Logs an array that includes the same
  // values as above, and also includes
  // ECMAScript built-ins like Math, Date,
  // and Object.
  console.log(
    Object.getOwnPropertyNames(this));
}

调整对库中 instanceof 的处理方式

在库中对作为参数传递的对象(来自另一个项目的函数)使用 instanceof 可能会产生假负例。在 V8 运行时中,项目及其库在不同的执行上下文中运行,因此具有不同的全局变量和原型链。

请注意,仅当您的库对并非在您的项目中创建的对象使用 instanceof 时,才会出现这种情况。对在项目中创建的对象(无论是在项目内的同一脚本还是不同脚本中)使用它应该能按预期运行。

如果在 V8 上运行的项目将您的脚本用作库,请检查您的脚本是否对从其他项目传递的参数使用了 instanceof。请根据您的用例调整 instanceof 的使用并使用其他可行的替代方案。

a instanceof b 的一个替代方案是使用 a 的构造函数,在这种情况下,您无需搜索整个原型链,只需检查构造函数即可。用法:a.constructor.name == "b"

以项目 A 和项目 B 为例,项目 A 使用项目 B 作为库。

//Rhino runtime

//Project A

function caller() {
   var date = new Date();
   // Returns true
   return B.callee(date);
}

//Project B

function callee(date) {
   // Returns true
   return(date instanceof Date);
}

      
//V8 runtime

//Project A

function caller() {
   var date = new Date();
   // Returns false
   return B.callee(date);
}

//Project B

function callee(date) {
   // Incorrectly returns false
   return(date instanceof Date);
   // Consider using return (date.constructor.name ==
   // “Date”) instead.
   // return (date.constructor.name == “Date”) -> Returns
   // true
}

另一种替代方案是引入一个函数,用于检查主项目中的 instanceof,并在调用库函数时传递该函数以及其他参数。然后,系统便可以使用传递的函数检查库中的 instanceof

//V8 runtime

//Project A

function caller() {
   var date = new Date();
   // Returns True
   return B.callee(date, date => date instanceof Date);
}

//Project B

function callee(date, checkInstanceOf) {
  // Returns True
  return checkInstanceOf(date);
}
      

调整将非共享资源传递给库的操作

非共享资源从主脚本传递到库的方式在 V8 运行时中有所不同。

在 Rhino 运行时中,传递非共享资源将不起作用。该库会改用自己的资源。

在 V8 运行时中,可以将非共享资源传递到库。库使用传递的非共享资源。

请勿将非共享资源作为函数参数传递。请务必在使用非共享资源的同一脚本中声明这些资源。

以项目 A 和项目 B 为例,项目 A 使用项目 B 作为库。在此示例中,PropertiesService 是非共享资源。

// Rhino runtime
// Project A
function testPassingNonSharedProperties() {
  PropertiesService.getScriptProperties()
      .setProperty('project', 'Project-A');
  B.setScriptProperties();
  // Prints: Project-B
  Logger.log(B.getScriptProperties(
      PropertiesService, 'project'));
}

//Project B function setScriptProperties() { PropertiesService.getScriptProperties() .setProperty('project', 'Project-B'); } function getScriptProperties( propertiesService, key) { return propertiesService.getScriptProperties() .getProperty(key); }

// V8 runtime
// Project A
function testPassingNonSharedProperties() {
  PropertiesService.getScriptProperties()
      .setProperty('project', 'Project-A');
  B.setScriptProperties();
  // Prints: Project-A
  Logger.log(B.getScriptProperties(
      PropertiesService, 'project'));
}

// Project B function setProperties() { PropertiesService.getScriptProperties() .setProperty('project', 'Project-B'); } function getScriptProperties( propertiesService, key) { return propertiesService.getScriptProperties() .getProperty(key); }

更新对独立脚本的访问权限

对于在 V8 运行时上运行的独立脚本,您至少需要为用户提供对该脚本的查看权限,以便脚本的触发器正常工作。