将脚本迁移到 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__ 函数,允许向任何 clas 添加自定义迭代器;为方便开发者,我们还将其添加到 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 中,标准 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 的构造函数,这是 a instanceof b 的一种替代方案。用法: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);
}
      

调整了向库传递非共享资源的操作

非共享资源从 main 脚本传递到库的方式在 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 运行时上运行的独立脚本,您至少要为用户提供对该脚本的查看权限,才能使脚本的触发器正常运行。