Skip to content

Instantly share code, notes, and snippets.

@yuchuanxi
Last active March 24, 2016 10:04
Show Gist options
  • Save yuchuanxi/fdd6dc20dd725a6cd54b to your computer and use it in GitHub Desktop.
Save yuchuanxi/fdd6dc20dd725a6cd54b to your computer and use it in GitHub Desktop.
Function overloading for Javascript
/**
*
* @authors yuChuanXi (http://yuchuanxi.com, wangfei.f2e@gmail.com)
* @date 2016-03-23 10:12:03
* @title title
* @description description
*/
'use strict';
// js 模拟重载函数 1
function addMethod ( obj, name, fn ) {
var old = obj[name];
obj[name] = function () {
if ( fn.length === arguments.length ) {
return fn.apply(this, arguments);
}
else {
return old.apply(this, arguments);
}
}
}
// js 模拟重载函数 2
var addMethod2 = (function () {
var
cache = {};
return function ( obj, name, fn ) {
obj[name] || (obj[name] = function () {
cache[arguments.length].apply(this, arguments);
});
cache[fn.length] = fn;
}
}());
// js 模拟重载函数 3
function addMethod3 ( obj, name, fn ) {
obj[name] || (obj[name] = function () {
addMethod3[arguments.length].apply(this,arguments);
});
addMethod3[fn.length] = fn;
}
// eg:
var
ninja1 = {},
ninja2 = {},
ninja3 = {};
addMethod(ninja1, 'whatever', function () {
console.log(111)
});
addMethod(ninja1, 'whatever', function (a) {
console.log(a)
});
addMethod(ninja1, 'whatever', function (a, b) {
console.log(a, b)
});
ninja1.whatever();
ninja1.whatever('a');
ninja1.whatever('a', 'b');
addMethod2(ninja2, 'whatever', function () {
console.log(111)
});
addMethod2(ninja2, 'whatever', function (a) {
console.log(a)
});
addMethod2(ninja2, 'whatever', function (a, b) {
console.log(a, b)
});
ninja2.whatever();
ninja2.whatever('a');
ninja2.whatever('a', 'b');
addMethod3(ninja3, 'whatever', function () {
console.log(111)
});
addMethod3(ninja3, 'whatever', function (a) {
console.log(a)
});
addMethod3(ninja3, 'whatever', function (a, b) {
console.log(a, b)
});
ninja3.whatever();
ninja3.whatever('a');
ninja3.whatever('a', 'b');
// 这样真的好吗
addMethod3(window, 'whatever', function () {
console.log(111)
});
addMethod3(window, 'whatever', function (a) {
console.log(a)
});
addMethod3(window, 'whatever', function (a, b) {
console.log(a, b)
});
whatever();
whatever('a');
whatever('a', 'b');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment