【问题标题】:How can I set type of arguments in JavaScript for Google closure compiler?如何在 JavaScript 中为 Google 闭包编译器设置参数类型?
【发布时间】:2013-12-19 00:39:26
【问题描述】:

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

考虑以下代码示例:

String.prototype.format = function(pattern){

var args = arguments.slice(1);

// other implementations are removed...

}

在这种情况下,Google Closure Compiler 告诉我参数没有方法切片。

其实它有一个方法名slice,但是Google Closure Compiler不能确定arguments数组的类型。

但在运行时代码运行良好

如何定义 Google Closure Compiler 的参数类型?

什么是最佳实践?

我测试了几种方法,但没有一个对我有用。

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

谢谢

【问题讨论】:

  • “但在运行时代码工作正常”不可能是正确的。参数没有“切片”方法。是什么让你认为它有效?在控制台中尝试:function foobar() {var args = arguments.slice(1)}; foob​​ar();结果:TypeError: Object # has no method 'slice'

标签: javascript google-closure-compiler


【解决方案1】:

arguments 不是一个数组(它是一个类似数组的对象),所以它不包含方法slice。你可以试试:var args = [].slice.call(arguments,1); 换句话说,调用arguments-object 的Array.slice-method 来创建一个真正的Array。在浏览器控制台中测试运行此代码:

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

See also

【讨论】:

  • 另一种(更详细但更简洁)的方式是:Array.prototype.slice.call(arguments, 1)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
  • 2020-05-13
相关资源
最近更新 更多