views:

69

answers:

3

I'm using Javascript with jQuery. I'd like to implement out params. In C#, it would look something like this:

/*
 * odp      the object to test
 * error    a string that will be filled with the error message if odp is illegal. Undefined otherwise.
 *
 * Returns  true if odp is legal.
 */
bool isLegal(odp, out error);

What is the best way to do something like this in JS? Objects?

function isLegal(odp, errorObj)
{
    // ...
    errorObj.val = "ODP failed test foo";
    return false;
}

Firebug tells me that the above approach would work, but is there a better way?

+5  A: 

I think this is pretty much the only way (but I am not a hardcore JavaScript programmer ;)).

What you could also consider is to use a callback function:

function onError(data) {
    // do stuff
}


function isLegal(odp, cb) {
    //...
    if(error) cb(error);
    return false;
}

isLegal(value, onError);
Felix Kling
+1, This is the more functional approach however it requires you to handle the error immediately. It is also the most common in my experience.
gradbot
+3  A: 

The callback approach mentioned by @Felix Kling is probably the best idea, but I've also found that sometimes it's easy to leverage Javascript object literal syntax and just have your function return an object on error:

function mightFail(param) {
  // ...
  return didThisFail ? { error: true, msg: "Did not work" } : realResult;
}

then when you call the function:

var result = mightFail("something");
if (result.error) alert("It failed: " + result.msg);

Not fancy and hardly bulletproof, but certainly it's OK for some simple situations.

Pointy
+1, This approach is common in JSON calls but I've rarely seen it in code.
gradbot
+1  A: 

Yes, as you yourself mentioned, objects are the best and only way to pass data by reference in JavaScript. I would keep your isLegal function as such and simply call it like this:

var error = {};
isLegal("something", error);
alert(error.val);
casablanca
+1, This style is the closest you're going to get to C#.
gradbot