I'm trying to understand something fairly simple I hope. How to pass optional parameters to a function or object in javascript by the parameter name.

for instance, what script.aculo.us does with their scripts.

syntax example:

Sortable.create('id_of_container',[options]);

live example:

Sortable.create('examplelist',{ghosting:true,constraint:false})

the object has a possibility of 5-10 parameters, all of which have default values, but when you create the object/call the function, you can specify the parameter by name, and pass a different value.

I realize script.aculo.us uses the prototype framework, but I don't quite understand their documentation on all of it. (I'm new it OO javascript).

Any help would be appreciated in either the idea of calling a function and passing optional parameters by name, or even how to use the prototype framework to make an object that has that functionality.

You can pass variable number of arguments to your function and expect it to dynamically handle them in a variety of ways. One of them would be to use the arguments property of Javascript Function object to grab hold of what was passed to your function at run-time.

[...]
function doSome() {
  for(var i = 0, max = arguments.length; i < max; ++i) {
    alert(arguments[i]);
  }
}
[...]
<body onload="doSome(1,2,3);">
</body>
[...]

Another way would be to use the Javascript object notation to enable the key-value enabled mechanism or passing parameters by name mechanism.

[...]
<head>
<script type="text/javascript">
function doSome(obj) {
  if(!obj)
    return;
  for(var key in obj) {
    alert(key + " => " + obj[key]);
  }
}
</script>
</head>
<body onload="doSome({name: 'sos', title: 'moderator'});">
[...]

The above code can also be used to set the property of a Javascript object on fly based on the property names; something like:

<head>
<script type="text/javascript">
function Person(name, title) {
  this.name = name;
  this.title = title;
}

Person.prototype.alert = function() {
  window.alert("Name: " + this.name + ", Title: " + this.title);
}

function doSome(obj) {
  if(!obj)
    return;
  var me = new Person();
  for(var key in obj) {
    me[key] = obj[key];
  }
  me.alert();
}
</script>
</head>
<body onload="doSome({name: 'sos', title: 'moderator'});">

Another way would be simply to pass an array and let the function handle the logic of looping through it and extracting meaningful data out of it. That all being said; if you have any Prototype.js or any other external library specific questions, you are better off asking them in the respective forums since it has better chance of getting expert replies.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.