如何在JavaScript中重载?
这个问题在这里已经有了答案:
在调用函数时,JavaScript不要求传递所有参数,因此可以像这样实现重载:
function foo(a, b, c) {
if (c === undefined) {
if (b === undefined) {
if (a === undefined) console.log("zero argument pass");
else console.log("one argument pass");
}
else console.log('two argument pass');
}
else console.log('three argument pass');
}
从http://ejohn.org/blog/javascript-method-overloading/
var namespace = {};
function addMethod(object, name, fn) {
var old = object[name];
object[name] = function() {
if (fn.length === arguments.length) {
return fn.apply(this, arguments);
} else if (typeof old === 'function') {
return old.apply(this, arguments);
}
};
}
addMethod(namespace, "foo", function (a) {
console.log("one argument pass");
});
addMethod(namespace, "foo", function (a, b) {
console.log("two arguments pass");
});
addMethod(namespace, "foo", function (a, b, c) {
console.log("three argument pass");
});
namespace.foo(1);
namespace.foo(1, 2);
namespace.foo(1, 2, 3);
var namespace = {};
function addMethod(object, name, fn) {
var old = object[name];
object[name] = function() {
if (fn.length === arguments.length) {
return fn.apply(this, arguments);
} else if (typeof old === 'function') {
return old.apply(this, arguments);
}
};
}
addMethod(namespace, "foo", function (a) {
document.write("one argument pass<br/>");
});
addMethod(namespace, "foo", function (a, b) {
document.write("two arguments pass<br/>");
});
addMethod(namespace, "foo", function (a, b, c) {
document.write("three argument pass<br/>");
});
namespace.foo(1);
namespace.foo(1, 2);
namespace.foo(1, 2, 3);
检查arity
function foo(a, b, opts) {
if (arguments.length === 1) {
console.log("one argument pass")
} else if (arguments.length === 2) {
console.log("two argument pass")
} else if (arguments.length === 3) {
console.log("three argument pass")
}
}
foo(1); // "one argument pass"
foo(1,2); // "two argument pass"
foo(1,2,3); // "three argument pass"
http://jsfiddle.net/moogs/m84fg8ac/2/
链接地址: http://www.djcxy.com/p/51969.html