如何最好地在JavaScript中实现params? [英] How best to implement out params in JavaScript?

查看:597
本文介绍了如何最好地在JavaScript中实现params?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jQuery中使用Javascript。我想实现params。在C#中,它看起来像这样:

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);

在JS中做这样的事情的最佳方法是什么?对象?

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告诉我上述方法可行,但有更好的方法?

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

推荐答案

@Felix Kling提到的回调方法可能是最好的主意,但我也发现有时它很容易利用Javascript对象文字语法,让你的函数在错误时返回一个对象:

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.

这篇关于如何最好地在JavaScript中实现params?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆