我对jQuery非常熟悉.我正在尝试为自己的目的编写常用方法.以下是一个示例:
$.extend({
add : function(a, b)
{
return a + b;
},
add : function(a, b, c)
{
return a + b + c;
}
});
Run Code Online (Sandbox Code Playgroud)
以上情况可能吗?我可以使用相同的扩展名称并传递不同的参数,如方法重载?
CMS*_*CMS 15
您试图在某些语言方法重载中执行某些类型的调用.
JavaScript不支持它.
JavaScript非常通用,可以让您以不同的方式实现此类功能.
对于您的特定示例,您的add函数,我建议您使用该arguments对象创建一个接受任意数量参数的函数.
jQuery.extend(jQuery, {
add: function (/*arg1, arg2, ..., argN*/) {
var result = 0;
$.each(arguments, function () {
result += this;
});
return result;
}
});
Run Code Online (Sandbox Code Playgroud)
然后你可以传递任意数量的参数:
alert(jQuery.add(1,2,3,4)); // shows 10
Run Code Online (Sandbox Code Playgroud)
对于更复杂的方法重载,您可以检测传递的参数数量及其类型,例如:
function test () {
if (arguments.length == 2) { // if two arguments passed
if (typeof arguments[0] == 'string' && typeof arguments[1] == 'number') {
// the first argument is a string and the second a number
}
}
//...
}
Run Code Online (Sandbox Code Playgroud)
查看下面的文章,它包含一个非常有趣的技术,利用一些JavaScript语言功能,如闭包,函数应用程序等,来模仿方法重载:
| 归档时间: |
|
| 查看次数: |
3570 次 |
| 最近记录: |