如何在JavaScript中为Google闭包编译器设置参数类型

How can I set type of arguments in JavaScript for Google closure compiler?

本文关键字:编译器 设置 参数 类型 闭包 Google JavaScript 中为      更新时间:2024-07-02

正如您所知,每个函数都是java脚本本身有一个名为"arguments"的变量,其中包含传递给该函数的所有参数。

考虑以下代码示例:

String.prototype.format = function(pattern){
var args = arguments.slice(1);
// other implementations are removed...
}

在这种情况下,GoogleClosureCompiler告诉我arguments没有方法切片。

事实上,它有一个方法名称切片,但Google闭包编译器无法确定参数数组的类型。

但在运行时代码运行良好

如何定义Google闭包编译器的参数类型?

什么是最佳实践?

我测试了几种方法,但没有一种对我有效

如果没有这个,我们的项目将无法正确编译,所以我们需要这个,谢谢

感谢

arguments不是数组(它是一个类似数组的对象),因此它不包含方法slice。你可以尝试:var args = [].slice.call(arguments,1);换句话说,调用arguments-对象的Array.slice-方法,从中创建一个真正的Array

function foo(){
  console.log([].slice.call(arguments,1));
}
foo(1,2,3); //=> logs [2,3]

另请参见