简体   繁体   中英

Can arguments be referenced in JavaScript using ColdFusion syntax?

In ColdFusion, if you want to reference

<cfargument name="x">

then you say:

arguments.x

In JavaScript, if you have a function:

var myFunction = function(x) {

then, is there a way to explicitly reference the arguments scope like maybe:

arguments[0].x

or something so that you're scoping everything.

There is no way to achieve the same functionality by using the arguments variable, as it holds no information on parameter names. To circumvent this, you could switch from using multiple parameters to one compound parameter object that holds actual parameter values in its members.

<script>
   function abc(params) {
    var x = params.x;
     var y = params["y"];
  }

   abc( { x: 10, y: "hello" });
</script>

This way however you lose some of the readability of the code at the function signature, plus you must provide param names on the calling side.

You can reference the arguments pseudo-variable, but the arguments are indexed by number, not by name. It's a good idea to avoid messing with arguments directly; a common idiom is to convert it to a real array:

var args = Array.slice.call(arguments, 0);

I'm afraid not. You can explicitly use x or arguments[0] but nothing more. Unless, as pointed out from others, you pass an object.

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