3

I'm trying to look up best practices and techniques for functions that accept "mixed" variables. This is similar to how the jQuery object accepts string, objects, and HTML Elements, and intelligently figures out what to do.

But I'm not sure what this pattern is called. How would a knowledgeable JavaScript developer refer to this technique?

For example:

function formatParams(mixed) {
    var params = {};
    switch (typeof mixed) {
        case 'string' :
            params = {query: mixed};
            break;
        case 'number' :
            params = {id: mixed};
            break;
        case 'function' :
            params = {callback: mixed}
            break;
        default: 
            params = mixed;
    }
    return params;
}
4

1 回答 1

1

我不知道这种模式是否有名字,但我想“通过多态参数进行准重载”可能是描述它的一种方式。它不是真正的多态性或重载(因此有限定词“准”),而是 JavaScript 具有动态类型的结果。

我们可能会在这里进入“主观”领域,但我通常不喜欢“混合”参数,因为当您处理参数时,这会导致模棱两可和可能的逻辑炸弹(基本上是一个巨大而笨拙的switch-case地方if-else)您尝试处理不同的参数组合)。

我更喜欢通过对象文字使用命名参数(或者至少是 JavaScript 允许的风格):

formatParams({
    stringParam: "string",
    numberParam: 42,
    booleanParam: true,
    functionParam: function() {
        ..
    }
});

然后在实际函数中,您可以检查每个单独的参数是否存在,并确保它是正确的类型:

function formatParams(options) {
    if(typeof options.stringParam !== "undefined" && typeof options.stringParam === "string") {
        //do what it is you want
    } else {
        throw "stringParam is expected to be of type 'string'.";
    }

    //and so on...
}

我发现这种形式的参数处理不太容易出错,并且更容易执行类型检查,还可以查看它们是否提供了所需的所有参数。

于 2013-07-11T20:32:18.297 回答