简体   繁体   中英

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

As you know every function is java script has a variable named 'arguments' in itself that contains all arguments passed to the function.

Consider following code sample:

String.prototype.format = function(pattern){

var args = arguments.slice(1);

// other implementations are removed...

}

In this scenario, Google Closure Compiler tells me that arguments has no method slice.

As a matter of fact, it has a method names slice, but Google Closure Compiler can not determinate the type of arguments array.

But at runtime the code works fine

How can I define the type of arguments for Google Closure Compiler?

What is a best practice?

I've tested several methods, but non of them worked for me.

Without this, our project will not compiled correctly, so we need this, thanks

Thanks

arguments is not an array (it's an array-like object), so it contains no method slice . You can try: var args = [].slice.call(arguments,1); In other words, call the Array.slice -method for the arguments -object to create a real Array out of it. To test run this code in a browser console:

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

See also

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM